Importing and Exporting Data#

PyExasol provides many Variants to import data to and export data from an Exasol database. To provide a consistent API, these variant have simple interfaces that follow the same pattern:

  • utilize the same inputs for generating the IMPORT and EXPORT statements. See Exasol Parameters.

  • use the HTTP Transport to reduce the fetching overhead associated with large data sets.

  • when the functionality of an external API is used (e.g. pandas), the variant will have an argument callback_params so that a user can define custom parameters to the required transformation function.

For more advanced users, check out the documentation on Parallel to parallelize importing or exporting data.

Warning

The Variants for importing and exporting data in Exasol are built on a shared callback pattern involving three concurrent Python threads:

  1. Main Thread: The caller of import_* or export_*, which processes data from that pipe.

  2. HTTP Thread: Consumes the HTTP[S] stream from the database and writes it to a pipe.

  3. SQL Thread: Executes the actual SQL IMPORT or EXPORT statement against the DB.

Error Handling Because these threads are interdependent, a failure in one typically triggers secondary exceptions in the others. Since PyExasol version 2.1.0, the library monitors all three sources for exceptions. Any caught exceptions are bundled into a custom exception (pyexasol.exceptions.ExaImportError or pyexasol.exceptions.ExaExportError), which also displays the tracebacks.

Variable Error Messages: Depending on the exact timing of the failure and the specific binary packages in use (which may introduce their own internal threading), the reported error messages may vary between executions of the same failing task. For instance, an error in the callback function may or may not propagate to the SQL thread when the exception was caught. Thus, between runs, you might catch between 1 to 2 sub-exceptions.

The examples on this page connect with a small helper, connect(), which is defined at the top of each example file. Replace the connection arguments with your own, see Configuration. The statements that need the connection are inside the with block.

def connect() -> pyexasol.ExaConnection:
    # Connect with compression enabled
    return pyexasol.connect(
        dsn=config.dsn,
        user=config.user,
        password=config.password,
        schema=config.schema,
        compression=True,
        websocket_sslopt=config.websocket_sslopt,
    )


Variants#

File#

For a complete, runnable example, see file.py.

Export#

See pyexasol.ExaConnection.export_to_file(). This method supports exporting data from an Exasol database into a file, path object, or file-like object opened in binary mode.

# Export to temporary file
with connect() as C:
    C.export_to_file(
        file,
        "users",
        export_params={
            "with_column_names": True,
            "comment": "Exporting users to temp file",
        },
    )

Import#

See pyexasol.ExaConnection.import_from_file(). This method supports importing data from a file, path object, or file-like object opened in binary mode.

Note

Files opened in text mode are not supported and will raise an error.

Note

The IMPORT statement only carries a ROW SEPARATOR clause when you pass row_separator, so by default the database uses LF. A file with CRLF line endings, which is what Python’s csv module, Excel and most RFC 4180 producers write, then keeps the carriage return in the last column of every row (silently for string columns, with an error for e.g. numeric columns), or fails with ETL-2105 when the last column is quoted. Files that already use LF need no row_separator. Otherwise, say which separator the file uses:

C.import_from_file('/test/my_file.csv', "users", import_params={"row_separator": "CRLF"})

or write the file with LF line endings, for example with csv.writer(f, lineterminator="\n").

# Import from temporary file
with connect() as C:
    C.import_from_file(file, "users_copy", import_params={"skip": 1})

Iterable#

For a complete, runnable example, see list.py.

Export#

See pyexasol.ExaConnection.export_to_list(). The source can be a table or a SQL query.

# Export to list
with connect() as C:
    users = C.export_to_list("users")

Import#

See pyexasol.ExaConnection.import_from_iterable(). Any iterable can be imported, such as a list of tuples or a generator. A generator is suitable for very big imports, as long as it returns rows one-by-one and does not run out of memory.

# Import from list (or any other iterable)
with connect() as C:
    C.import_from_iterable(users, "users_copy")

Pandas#

For a complete, runnable example, see pandas_dataframe.py.

Export#

See pyexasol.ExaConnection.export_to_pandas().

# Export from Exasol table into pandas.DataFrame
with connect() as C:
    pd = C.export_to_pandas("users")
# Export from SQL query
with connect() as C:
    pd = C.export_to_pandas(
        "SELECT user_id, user_name FROM users WHERE user_id >= 5000"
    )

Import#

See pyexasol.ExaConnection.import_from_pandas().

# Import from pandas DataFrame into Exasol table
with connect() as C:
    C.import_from_pandas(pd, "users_copy")

Parquet#

For a complete, runnable example, see parquet_file.py.

Export#

See pyexasol.ExaConnection.export_to_parquet(). dst is the local directory to write the parquet file(s) to, given as a str or a pathlib.Path. By default, it must not exist yet or must be empty. To export into a directory which already contains files, set callback_params["existing_data_behavior"] to "overwrite_or_ignore" or "delete_matching". Otherwise, a ValueError is raised before the export starts. Further callback_params are passed to pyarrow.dataset.write_dataset().

# Export from Exasol table into the temporary directory into a local parquet file.
# The data is transferred as CSV, so BOOLEAN columns are exported as 1/0 and read as
# int64 by default. The native Parquet import (Exasol 2026.1.0 and newer) rejects
# int64 for BOOLEAN columns, so we export booleans as true/false to get a bool column.
with connect() as C:
    C.export_to_parquet(
        dst=directory_path,
        query_or_table="users",
        export_params={"boolean": "true/false"},
    )

# Export from SQL query
basename_template = "second-export_{i}.parquet"
with connect() as C:
    C.export_to_parquet(
        dst=directory_path,
        query_or_table="SELECT user_id, user_name FROM users WHERE user_id >= 5000",
        callback_params={
            # for this example, it is ok if we use a directory where data is already stored
            "existing_data_behavior": "overwrite_or_ignore",
            # for this example, we'd want to change the basename_template so that first
            # exported file is retained
            "basename_template": basename_template,
        },
    )

Import#

See pyexasol.ExaConnection.import_from_parquet(). The source can be:

  • a str representing a filepath which already contains a glob pattern, as in the example below,

  • a list[pathlib.Path] of specific parquet files to load, or

  • a pathlib.Path, which can be either a file or a directory. If it is a directory, all files matching the pattern *.parquet are processed.

# import_from_parquet allows for users to specify parquet files in multiple ways;
# this example usage using a string with a glob pattern is just one of them.
filepath_glob = f"{directory_path}/*.parquet"
# On Exasol 2026.1.0 and newer, this uses the native Parquet import. It does not
# convert between types, so the Parquet column types must match the table (e.g. a
# Parquet double cannot be imported into a DECIMAL column). It imports the files in
# batches of max_files_per_batch (default 1), the only callback_params key it accepts.
# Pass native=False to use the callback-based import instead, which converts types
# through CSV. See import_from_parquet() for all differences.
# Import from temporary directory with a local parquet file into an Exasol table
with connect() as C:
    C.import_from_parquet(source=filepath_glob, table="users_copy")

Polars#

For a complete, runnable example, see polars_dataframe.py.

Export#

See pyexasol.ExaConnection.export_to_polars().

# Export from Exasol table into polars.DataFrame
with connect() as C:
    df = C.export_to_polars("users")
# Export from SQL query
with connect() as C:
    df = C.export_to_polars(
        "SELECT user_id, user_name FROM users WHERE user_id >= 5000"
    )

Import#

See pyexasol.ExaConnection.import_from_polars().

# Import from polars DataFrame into Exasol table
with connect() as C:
    C.import_from_polars(df, "users_copy")

A LazyFrame can be imported the same way.

# Alternatively use polars LazyFrame the same way (this appends to the rows imported above)
with connect() as C:
    lf = df.lazy()
    C.import_from_polars(lf, "users_copy")

Write a Custom Variant#

Note

A full collection of pre-defined callback functions is available in the pyexasol.callback module. Their usage by the pyexasol.ExaConnection class is documented in the Variants section.

For a complete, runnable example, see customization.py.

Export#

Example of a callback that keeps the first two lines of the exported CSV stream and discards the rest.

# Export to custom callback
def my_export_callback(pipe, dst):
    # Save 2 first lines
    lines = [pipe.readline(), pipe.readline()]

    # Dump everything else to /dev/null
    dev_null = open(os.devnull, "wb")
    shutil.copyfileobj(pipe, dev_null)
    dev_null.close()

    return lines


# Run EXPORT using the custom callback function
with connect() as C:
    result = C.export_to_callback(my_export_callback, None, "users")

Import#

Example of a callback that writes lines into the pipe for IMPORT.

# Import from custom callback
def my_import_callback(pipe, src):
    for line in src:
        pipe.write(line)


# Run IMPORT using the custom callback function
with connect() as C:
    C.import_from_callback(my_import_callback, result, "users_copy")