### Main script for MFA authentication examples Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect Command-line interface to run different MFA authentication examples. Usage: python auth_by_mfa.py [passcode]. Examples include push, passcode, password, callback, and cache. ```python if __name__ == "__main__": import sys print("Snowflake MFA Authentication Examples") print("=" * 40) if len(sys.argv) < 2: print( """ Usage: python auth_by_mfa.py [passcode] Examples: python auth_by_mfa.py push # MFA with push notification python auth_by_mfa.py passcode 123456 # MFA with TOTP passcode python auth_by_mfa.py password 123456 # MFA with passcode in password python auth_by_mfa.py callback # MFA with callback function python auth_by_mfa.py cache # MFA with token caching """ ) sys.exit(1) example = sys.argv[1].lower() if example == "push": connect_with_mfa_push() elif example == "passcode": if len(sys.argv) < 3: print("Error: Please provide a passcode") sys.exit(1) connect_with_mfa_passcode(sys.argv[2]) elif example == "password": if len(sys.argv) < 3: print("Error: Please provide a passcode") sys.exit(1) connect_with_passcode_in_password(sys.argv[2]) elif example == "callback": connect_with_mfa_callback() elif example == "cache": connect_with_mfa_token_caching() else: print(f"Unknown example: {example}") sys.exit(1) ``` -------------------------------- ### Get login information from environment variables Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect Example of retrieving login information such as password and warehouse from environment variables. ```python PASSWORD = os.getenv('SNOWSQL_PWD') WAREHOUSE = os.getenv('WAREHOUSE') ... ``` -------------------------------- ### Run a query Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-asyncio Example of executing a query and fetching results using the asyncio connector. ```python async with conn.cursor() as cur: await cur.execute("SELECT col1, col2 FROM testtable") async for col1, col2 in cur: print(f"{col1}, {col2}") ``` -------------------------------- ### Main example class to create and query a table Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example This is the main example program that uses the Snowflake Python Connector. It creates a table named test_table, inserts two rows, and then queries the table, printing each row. The main block instantiates the class and calls its main method. ```python import sys # -- (> ---------------------- SECTION=import_connector --------------------- import snowflake.connector # -- <) ---------------------------- END_SECTION ---------------------------- # Import the base class that contains methods used in many tests and code # examples. from python_veritas_base import python_veritas_base class python_connector_example (python_veritas_base): """ PURPOSE: This is a simple example program that shows how to use the Snowflake Python Connector to create and query a table. """ def __init__(self): pass def do_the_real_work(self, conn): """ INPUTS: conn is a Connection object returned from snowflake.connector.connect(). """ print("\nCreating table test_table...") # -- (> ----------------------- SECTION=create_table --------------------- conn.cursor().execute( "CREATE OR REPLACE TABLE " "test_table(col1 integer, col2 string)") conn.cursor().execute( "INSERT INTO test_table(col1, col2) VALUES " + " (123, 'test string1'), " + " (456, 'test string2')") # -- <) ---------------------------- END_SECTION ------------------------- print("\nSelecting from test_table...") # -- (> ----------------------- SECTION=querying_data -------------------- cur = conn.cursor() try: cur.execute("SELECT col1, col2 FROM test_table ORDER BY col1") for (col1, col2) in cur: print('{0}, {1}'.format(col1, col2)) finally: cur.close() # -- <) ---------------------------- END_SECTION ------------------------- # ============================================================================ if __name__ == '__main__': test_case = python_connector_example() test_case.main(sys.argv) ``` -------------------------------- ### Install and test Snowflake Connector for Python 5.0.0 Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-upgrade Install the connector, verify the version, and run tests with deprecation warnings treated as errors. The printed version should be 5.0.0. ```bash pip install --upgrade snowflake-connector-python python -c "import snowflake.connector; print(snowflake.connector.__version__)" python -W error::DeprecationWarning -m pytest ``` -------------------------------- ### Install legacy secure-local-storage and pandas extras (pre-5.0) Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-pandas Before version 5.0, Linux token caching required the secure-local-storage extra. This command installs both that extra and pandas. See the MFA token caching documentation for details. ```bash pip install "snowflake-connector-python[secure-local-storage,pandas]" ``` -------------------------------- ### Longer Snowflake Python Connector example Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example A comprehensive example demonstrating connecting to Snowflake, creating warehouse/database/schema, creating tables, inserting data, copying from internal and external stages, querying, binding parameters, retrieving column names, catching syntax errors, retrieving query ID, and closing the connection. ```python #!/usr/bin/env python # # Snowflake Connector for Python Sample Program # # Logging import logging logging.basicConfig( filename='/tmp/snowflake_python_connector.log', level=logging.INFO) import snowflake.connector # Connecting to Snowflake con = snowflake.connector.connect() # Creating a database, schema, and warehouse if none exists con.cursor().execute("CREATE WAREHOUSE IF NOT EXISTS tiny_warehouse") con.cursor().execute("CREATE DATABASE IF NOT EXISTS testdb") con.cursor().execute("USE DATABASE testdb") con.cursor().execute("CREATE SCHEMA IF NOT EXISTS testschema") # Using the database, schema and warehouse con.cursor().execute("USE WAREHOUSE tiny_warehouse") con.cursor().execute("USE SCHEMA testdb.testschema") # Creating a table and inserting data con.cursor().execute( "CREATE OR REPLACE TABLE " "testtable(col1 integer, col2 string)") con.cursor().execute( "INSERT INTO testtable(col1, col2) " "VALUES(123, 'test string1'),(456, 'test string2')") # Copying data from internal stage (for testtable table) con.cursor().execute("PUT file:///tmp/data0/file* @%testtable") con.cursor().execute("COPY INTO testtable") # Copying data from external stage (S3 bucket - # replace with the name of your bucket) con.cursor().execute(""" COPY INTO testtable FROM s3:///data/ STORAGE_INTEGRATION = myint FILE_FORMAT=(field_delimiter=',') """) # Querying data cur = con.cursor() try: cur.execute("SELECT col1, col2 FROM testtable") for (col1, col2) in cur: print('{0}, {1}'.format(col1, col2)) finally: cur.close() # Binding data con.cursor().execute( "INSERT INTO testtable(col1, col2) " "VALUES(%(col1)s, %(col2)s)", { 'col1': 789, 'col2': 'test string3', }) # Retrieving column names cur = con.cursor() cur.execute("SELECT * FROM testtable") print(','.join([col[0] for col in cur.description])) # Catching syntax errors cur = con.cursor() try: cur.execute("SELECT * FROM testtable") except snowflake.connector.errors.ProgrammingError as e: # default error message print(e) # user error message print('Error {0} ({1}): {2} ({3})'.format(e.errno, e.sqlstate, e.msg, e.sfqid)) finally: cur.close() # Retrieving the Snowflake query ID cur = con.cursor() cur.execute("SELECT * FROM testtable") print(cur.sfqid) # Closing the connection con.close() ``` -------------------------------- ### Unsafe SQL binding with .format() (UNSAFE EXAMPLE) Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Unsafe example using Python .format() to bind data, risking SQL injection. ```python # Binding data (UNSAFE EXAMPLE) con.cursor().execute( "INSERT INTO testtable(col1, col2) " "VALUES({col1}, '{col2}')".format( col1=789, col2='test string3') ) ``` -------------------------------- ### Unsafe SQL binding with % formatting and positional args (UNSAFE EXAMPLE) Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Unsafe example using Python % formatting with positional arguments to bind data, risking SQL injection. ```python # Binding data (UNSAFE EXAMPLE) con.cursor().execute( "INSERT INTO testtable(col1, col2) " "VALUES(%d, '%s')" % ( 789, 'test string3' )) ``` -------------------------------- ### Unsafe SQL binding with % formatting (UNSAFE EXAMPLE) Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Unsafe example using Python % formatting to bind data, risking SQL injection. ```python # Binding data (UNSAFE EXAMPLE) con.cursor().execute( "INSERT INTO testtable(col1, col2) " "VALUES(%(col1)d, '%(col2)s')" % { 'col1': 789, 'col2': 'test string3' }) ``` -------------------------------- ### Set warehouse, database, and schema Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Use these commands to set the warehouse, database, and schema for the session. The example uses the database 'testdb_mg', schema 'testschema_mg', and warehouse 'tiny_warehouse_mg'. ```python conn.cursor().execute("USE WAREHOUSE tiny_warehouse_mg") conn.cursor().execute("USE DATABASE testdb_mg") conn.cursor().execute("USE SCHEMA testdb_mg.testschema_mg") ``` -------------------------------- ### connect() - account parameter usage Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api Examples of using the account parameter with the connect method, showing both account name and account locator formats. ```APIDOC ## connect() - account parameter usage ### Description Examples of using the account parameter with the connect method, showing both account name and account locator formats. ### Method connect ### Parameters #### account (string) - Required - Specify your account identifier. The account identifier does not include the `snowflakecomputing.com` domain name. Snowflake automatically appends this when creating the connection. ### Request Example ```python ctx = snowflake.connector.connect( user='', password='', account='myorganization-myaccount', ... ) ``` ### Request Example (account locator) ```python ctx = snowflake.connector.connect( user='', password='', account='xy12345', ... ) ``` ``` -------------------------------- ### Install pandas extra for Snowflake Connector for Python Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-pandas Install the pandas-compatible version of the connector. The square brackets are required and must be quoted to prevent wildcard interpretation. Token caching is included; no secure-local-storage extra is published. ```bash pip install "snowflake-connector-python[pandas]" ``` -------------------------------- ### Use DictCursor Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-asyncio Example of using DictCursor to fetch rows as dictionaries. ```python from snowflake.connector.aio import DictCursor async with conn.cursor(DictCursor) as cur: await cur.execute("SELECT col1, col2 FROM testtable") print(await cur.fetchone()) ``` -------------------------------- ### Section marker example Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Shows the format of section markers used in the sample code to identify importable sections. These markers are not required in user code. ```python # -- (> ---------------------- SECTION=import_connector --------------------- ... # -- <) ---------------------------- END_SECTION ---------------------------- ``` -------------------------------- ### Run python_connector_example.py with command-line arguments Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Executes the sample program with required arguments for warehouse, database, schema, account, and user. Warning: this deletes the warehouse, database, and schema at the end of the program, so do not use an existing database name. ```bash python3 python_connector_example.py --warehouse --database --schema --account myorganization-myaccount --user MyUserName ``` -------------------------------- ### Install the latest Python Connector with pip Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-install Use this command to install the latest version of the Snowflake Python Connector. Note that pip install --upgrade snowflake-connector-python installs version 5.x, which may break Snowpark for Python, Snowflake ML, Snowflake SQLAlchemy, and Snowflake CLI. Pin a release before 5.0 if you need the previous connector, for example snowflake-connector-python>=4,<5. ```bash pip install snowflake-connector-python ``` -------------------------------- ### Set up test environment Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Sets up the environment for running a test by creating a temporary warehouse, database, and schema. This method can be overridden for specific test/demo needs. ```python def set_up(self, connection): """ PURPOSE: Set up to run a test. You can override this method with one appropriate to your test/demo. """ # Create a temporary warehouse, database, and schema. self.create_warehouse_database_and_schema(connection) ``` -------------------------------- ### Retrieve result batches as PyArrow tables Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-distributed-fetch Use fetch_arrow_all() to get a PyArrow table with all results, or fetch_arrow_batches() to iterate over PyArrow tables for each result batch. The example shows both methods after executing a query. ```python with connect(...) as conn: with conn.cursor() as cur: # Execute a query. cur.execute('select seq4() as n from table(generator(rowcount => 100000));') # Return a PyArrow table containing all of the results. table = cur.fetch_arrow_all() # Iterate over a list of PyArrow tables for result batches. for table_for_batch in cur.fetch_arrow_batches(): my_pyarrow_table_processing_function(table_for_batch) ``` -------------------------------- ### Get AWS credentials from environment variables Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect Example of retrieving AWS access key ID and secret access key from environment variables, needed when copying data from your own Amazon S3 bucket. ```python import os AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') ``` -------------------------------- ### Retrieve result batches as ResultBatch objects Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-distributed-fetch After executing a query, call get_result_batches() on the Cursor object to get a list of ResultBatch objects. The example splits the list into two lists to distribute work between two workers. ```python with connect(...) as conn: with conn.cursor() as cur: # Execute a query. cur.execute('select seq4() as n from table(generator(rowcount => 100000));') # Get the list of result batches result_batch_list = cur.get_result_batches() # Get the number of result batches in the list. num_result_batches = len(result_batch_list) # Split the list of result batches into two # to distribute the work of fetching results # between two workers. result_batch_list_1 = result_batch_list[:: 2] result_batch_list_2 = result_batch_list[1 :: 2] ``` -------------------------------- ### Base class methods for setup and cleanup Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example These methods are part of the python_veritas_base class. The default run method executes a simple SQL command (SELECT PI()) to verify the connection. The create_warehouse_database_and_schema method creates a warehouse, database, and schema if they don't exist, and then uses them. The drop_warehouse_database_and_schema method drops the schema, database, and warehouse. The clean_up method calls the drop method. ```python """ PURPOSE: Your sub-class should override this to include the code required for your documentation sample or your test case. This default method does a very simple self-test that shows that the connection was successful. """ # Create a cursor for this connection. cursor1 = conn.cursor() # This is an example of an SQL statement we might want to run. command = "SELECT PI()" # Run the statement. cursor1.execute(command) # Get the results (should be only one): for row in cursor1: print(row[0]) # Close this cursor. cursor1.close() def clean_up(self, connection): """ PURPOSE: Clean up after a test. You can override this method with one appropriate to your test/demo. """ # Create a temporary warehouse, database, and schema. self.drop_warehouse_database_and_schema(connection) def create_warehouse_database_and_schema(self, conn): """ PURPOSE: Create the temporary schema, database, and warehouse that we use for most tests/demos. """ # Create a database, schema, and warehouse if they don't already exist. print("\nCreating warehouse, database, schema...") # -- (> ------------- SECTION=create_warehouse_database_schema ------- conn.cursor().execute("CREATE WAREHOUSE IF NOT EXISTS tiny_warehouse_mg") conn.cursor().execute("CREATE DATABASE IF NOT EXISTS testdb_mg") conn.cursor().execute("USE DATABASE testdb_mg") conn.cursor().execute("CREATE SCHEMA IF NOT EXISTS testschema_mg") # -- <) ---------------------------- END_SECTION --------------------- # -- (> --------------- SECTION=use_warehouse_database_schema -------- conn.cursor().execute("USE WAREHOUSE tiny_warehouse_mg") conn.cursor().execute("USE DATABASE testdb_mg") conn.cursor().execute("USE SCHEMA testdb_mg.testschema_mg") # -- <) ---------------------------- END_SECTION --------------------- def drop_warehouse_database_and_schema(self, conn): """ PURPOSE: Drop the temporary schema, database, and warehouse that we create for most tests/demos. """ # -- (> ------------- SECTION=drop_warehouse_database_schema --------- conn.cursor().execute("DROP SCHEMA IF EXISTS testschema_mg") conn.cursor().execute("DROP DATABASE IF EXISTS testdb_mg") conn.cursor().execute("DROP WAREHOUSE IF EXISTS tiny_warehouse_mg") # -- <) ---------------------------- END_SECTION --------------------- # ---------------------------------------------------------------------------- if __name__ == '__main__': pvb = python_veritas_base() pvb.main(sys.argv) ``` -------------------------------- ### Sample program output Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Expected output when running the sample program, showing connection, object creation, table creation, selection results, and connection closing. ```text Connecting... Creating warehouse, database, schema... Creating table test_table... Selecting from test_table... 123, test string1 456, test string2 Closing connection... ``` -------------------------------- ### Install FIPS-supporting version on Windows PowerShell Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-install Set the SNOWFLAKE_FIPS environment variable in PowerShell, then run the same install command as on Linux/macOS. This version doesn't build on Windows on ARM. On Windows, the install places the module's shared libraries next to the connector. ```powershell $env:SNOWFLAKE_FIPS = "1" python -m pip install --no-binary snowflake-connector-python snowflake-connector-python ``` -------------------------------- ### write_pandas example: Write pandas DataFrame to Snowflake table Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api Example from the write_pandas function documentation. It creates a connection, builds a DataFrame, and writes it to the 'customers' table. The connection object is created with placeholder arguments. ```python import pandas from snowflake.connector.pandas_tools import write_pandas # Create the connection to the Snowflake database. cnx = snowflake.connector.connect(...) # Create a DataFrame containing data about customers df = pandas.DataFrame([('Mark', 10), ('Luke', 20)], columns=['name', 'balance']) # Write the data from the DataFrame to the table named "customers". success, nchunks, nrows, _ = write_pandas(cnx, df, 'customers') ``` -------------------------------- ### executemany with qmark binding Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api Example showing how to use executemany with qmark binding. Requires setting connector.paramstyle='qmark'. Demonstrates passing a list of lists and a tuple of tuples as sequences of parameters. Internally, multiple execute calls are made and the last result set remains. ```python # This example uses qmark (question mark) binding, so # you must configure the connector to use this binding style. from snowflake import connector connector.paramstyle='qmark' stmt1 = "create table testy (V1 varchar, V2 varchar)" cs.execute(stmt1) # A list of lists sequence_of_parameters1 = [ ['Smith', 'Ann'], ['Jones', 'Ed'] ] # A tuple of tuples sequence_of_parameters2 = ( ('Cho', 'Kim'), ('Cooper', 'Pat') ) stmt2 = "insert into testy (v1, v2) values (?, ?)" cs.executemany(stmt2, sequence_of_parameters1) cs.executemany(stmt2, sequence_of_parameters2) ``` -------------------------------- ### Open a connection with async with Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-asyncio Use async with snowflake.connector.aio.connect() to open a session when entering the block and close it when leaving. The connection parameters are the same as for the synchronous connector. ```python async with snowflake.connector.aio.connect() as conn: ... ``` -------------------------------- ### Connect using account locator Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api Example of connecting to Snowflake using an account locator (e.g., 'xy12345'). This example uses an account in the AWS US West (Oregon) region; other regions or cloud providers may require additional segments after the account locator. ```python ctx = snowflake.connector.connect( user='', password='', account='xy12345', ... ) ``` -------------------------------- ### Create warehouse, database, and schema with Python Connector Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Creates a warehouse named tiny_warehouse_mg, a database named testdb_mg, and a schema named testschema_mg. Executes USE DATABASE before CREATE SCHEMA to ensure the schema is created in the correct database. ```python conn.cursor().execute("CREATE WAREHOUSE IF NOT EXISTS tiny_warehouse_mg") conn.cursor().execute("CREATE DATABASE IF NOT EXISTS testdb_mg") conn.cursor().execute("USE DATABASE testdb_mg") conn.cursor().execute("CREATE SCHEMA IF NOT EXISTS testschema_mg") ``` -------------------------------- ### Create a Snowflake connection from environment and command-line parameters Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Creates a connection to Snowflake using account identifier and login information from environment variables and command-line parameters. Requires at least 11 command-line arguments and the SNOWSQL_PWD environment variable. Exits with error codes -1 and -2 on missing parameters or password. ```python def create_connection(self, argv): """ PURPOSE: This gets account identifier and login information from the environment variables and command-line parameters, connects to the server, and returns the connection object. INPUTS: argv: This is usually sys.argv, which contains the command-line parameters. It could be an equivalent substitute if you get the parameter information from another source. RETURNS: A connection. """ # Get account identifier and login information from environment variables and command-line parameters. # For information about account identifiers, see # https://docs.snowflake.com/en/user-guide/admin-account-identifier.html . # -- (> ----------------------- SECTION=set_login_info --------------- # Get the password from an appropriate environment variable, if # available. PASSWORD = os.getenv('SNOWSQL_PWD') # Get the other login info etc. from the command line. if len(argv) < 11: msg = "ERROR: Please pass the following command-line parameters:\n" msg += "--warehouse --database --schema " msg += "--user --account " print(msg) sys.exit(-1) else: connection_parameters = self.args_to_properties(argv) USER = connection_parameters["user"] ACCOUNT = connection_parameters["account"] WAREHOUSE = connection_parameters["warehouse"] DATABASE = connection_parameters["database"] SCHEMA = connection_parameters["schema"] # Optional: for internal testing only. try: PORT = connection_parameters["port"] except: PORT = "" try: PROTOCOL = connection_parameters["protocol"] except: PROTOCOL = "" # If the password is set by both command line and env var, the # command-line value takes precedence over (is written over) the # env var value. # If the password wasn't set either in the environment var or on # the command line... if PASSWORD is None or PASSWORD == '': print("ERROR: Set password, e.g. with SNOWSQL_PWD environment variable") sys.exit(-2) # -- <) ---------------------------- END_SECTION --------------------- # Optional diagnostic: #print("USER:", USER) #print("ACCOUNT:", ACCOUNT) #print("WAREHOUSE:", WAREHOUSE) #print("DATABASE:", DATABASE) #print("SCHEMA:", SCHEMA) #print("PASSWORD:", PASSWORD) #print("PROTOCOL:" "'" + PROTOCOL + "'") #print("PORT:" + "'" + PORT + "'") print("Connecting...") # If the PORT is set but the protocol is not, we ignore the PORT (bug!!). if PROTOCOL is None or PROTOCOL == "" or PORT is None or PORT == "": # -- (> ------------------- SECTION=connect_to_snowflake --------- conn = snowflake.connector.connect( user=USER, password=PASSWORD, account=ACCOUNT, warehouse=WAREHOUSE, database=DATABASE, schema=SCHEMA ) # -- <) ---------------------------- END_SECTION ----------------- else: conn = snowflake.connector.connect( user=USER, password=PASSWORD, account=ACCOUNT, warehouse=WAREHOUSE, database=DATABASE, schema=SCHEMA, # Optional: for internal testing only. protocol=PROTOCOL, port=PORT ) return conn ``` -------------------------------- ### Convert ResultBatch to pandas DataFrame and PyArrow table Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-distributed-fetch Use `to_pandas()` to get a pandas DataFrame and `to_arrow()` to get a PyArrow table from a result batch. Requires the pandas-compatible version of the Snowflake Connector for Python for `to_pandas()`. Works on all batch types, including JSON batches. ```python with conn_cnx as con: with con.cursor() as cur: cur.execute("select col1 from table") batches = cur.get_result_batches() # Get the row from the ResultBatch as a pandas DataFrame. dataframe = batches[0].to_pandas() # Get the row from the ResultBatch as a PyArrow table. table = batches[0].to_arrow() ``` -------------------------------- ### Run a query Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-asyncio Demonstrates how to execute a query using the AsyncIO cursor and iterate over the results. ```APIDOC ## Run a query ### Description Executes a query and iterates over the result set asynchronously. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters - **sql** (str) - Required - The SQL query to execute. - **params** (tuple) - Optional - Bound values for the query parameters. ### Request Example ```python async with conn.cursor() as cur: await cur.execute( "SELECT col1, col2 FROM testtable WHERE col1 > %s", (100,), ) async for col1, col2 in cur: print(f"{col1}, {col2}") ``` ### Response #### Success Response - **rows** (iterator) - An asynchronous iterator of result rows. #### Response Example ```python async for col1, col2 in cur: print(f"{col1}, {col2}") ``` ``` -------------------------------- ### Verify FIPS status of installed connector Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-install Use this Python code to confirm whether the installed connector is FIPS-supporting. The value is True for a FIPS-supporting version and False for a standard version. A true value means this process loaded that version and its TLS provider is the FIPS module; it does not certify the connector. ```python import snowflake.connector status = snowflake.connector.get_fips_status() print(status.is_fips) ``` -------------------------------- ### Import snowflake.connector module Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect Execute this command to import the snowflake.connector module. ```python import snowflake.connector ``` -------------------------------- ### Run queries concurrently Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-asyncio Example of running multiple queries concurrently using asyncio.gather. ```python async def fetch_rows(conn, sql): async with conn.cursor() as cur: await cur.execute(sql) return await cur.fetchall() async with snowflake.connector.aio.connect() as conn: results = await asyncio.gather( fetch_rows(conn, "SELECT 1"), fetch_rows(conn, "SELECT 2"), ) ``` -------------------------------- ### Cursor.execute(command [, parameters][, timeout][, file_stream]) Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api Prepares and executes a database command. Supports optional parameters for binding data, timeout, and file stream for PUT commands. ```APIDOC ## Cursor.execute(command [, parameters][, timeout][, file_stream]) ### Description Prepares and executes a database command. ### Method execute(command [, parameters][, timeout][, file_stream]) ### Parameters - **command** (string) - Required - A string containing the SQL statement to execute. - **parameters** (list or dict) - Optional - If you used parameters for binding data in the SQL statement, set this to the list or dictionary of variables that should be bound to those parameters. - **timeout** (int) - Optional - Number of seconds to wait for the query to complete. If the query has not completed after this time has passed, the query should be aborted. - **file_stream** (file-like object) - Optional - When executing a PUT command, you can use this parameter to upload an in-memory file-like object (e.g. the I/O object returned from the Python `open()` function), rather than a file on the filesystem. Set this parameter to that I/O object. ### Returns Returns the reference of a Cursor object. ### Example ```python cursor.execute( "PUT file://this_directory_path/is_ignored/myfile.csv @mystage", file_stream=) ``` ``` -------------------------------- ### snowflake.connector.connect Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect Establishes a connection to Snowflake. This example shows setting connection timeout parameters. ```APIDOC ## snowflake.connector.connect ### Description Establishes a connection to Snowflake. This example shows setting connection timeout parameters. ### Method connect ### Parameters #### Connection Parameters - `login_timeout` (int) - Optional - How long, in seconds, to keep retrying the login. Default is 120. - `query_timeout` (int) - Optional - Wall-clock timeout, in seconds, for query execution including retries. Default is 0 (no timeout). - `request_timeout` (int) - Optional - Wall-clock timeout, in seconds, for other operations (e.g., closing session, heartbeats) including retries. Default is 120. 0 means no timeout. - `connect_timeout` (int) - Optional - Timeout, in seconds, for establishing a single HTTP connection. No default cap. - `retry_timeout` (int) - Optional - Hard wall-clock cap, in seconds, on one HTTP attempt, including the response body. No default cap. ### Request Example ```python conn = snowflake.connector.connect( login_timeout=60, query_timeout=30, request_timeout=30, retry_timeout=10, ) ``` ### Notes - `network_timeout` and `socket_timeout` are deprecated names. Passing either emits a `DeprecationWarning`. - `network_timeout` value is copied to both `query_timeout` and `request_timeout` unless you set one of those yourself. - `socket_timeout` value is copied to both `connect_timeout` and `retry_timeout`. ``` -------------------------------- ### Using qmark binding with connection paramstyle Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Sets paramstyle to 'qmark' in connection parameters and executes an INSERT with ? placeholders. Requires the snowflake.connector.connect call and a table named testtable2. ```python from snowflake.connector import connect connection_parameters = { 'account': 'xxxxx', 'user': 'xxxx', 'password': 'xxxxxx', "host": "xxxxxx", "port": 443, 'protocol': 'https', 'warehouse': 'xxx', 'database': 'xxx', 'schema': 'xxx', 'paramstyle': 'qmark' # note paramstyle setting here at connection level } con = connect(**connection_parameters) con.cursor().execute( "INSERT INTO testtable2(col1,col2,col3) " "VALUES(?,?,?)", ( 987, 'test string4', ("TIMESTAMP_LTZ", datetime.now()) ) ) ``` -------------------------------- ### Fetch a single row with fetchone Source: https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example Use fetchone() to get a single row from the result set. ```python col1, col2 = con.cursor().execute("SELECT col1, col2 FROM testtable").fetchone() print('{0}, {1}'.format(col1, col2)) ```