Sign inGet started
← Back to all guides

How to use Python in Snowflake

By Nick Barth

Updated on March 6, 2024

Using Python with Snowflake can streamline data processing and analytics.

To get started:

  1. Install the `snowflake-connector-python` package using `pip`.
  2. Import the connector in your Python script: `import snowflake.connector`.
  3. Establish a connection to your Snowflake instance using your account credentials.
  4. Execute SQL statements by creating a cursor object and calling the `execute` method with your query.
  5. Fetch results using methods like `fetchone()`, `fetchall()`, or `fetch_pandas_all()` for integrating with pandas DataFrames. 
  6. Close the connection to free up resources.

Python script to query Snowflake and fetch results

import snowflake.connector

Connect to Snowflake

conn = snowflake.connector.connect(
⁠
⁠    user='YOUR_USERNAME',
⁠
⁠    password='YOUR_PASSWORD',
⁠
⁠    account='YOUR_ACCOUNT',
⁠
⁠    warehouse='YOUR_WAREHOUSE',
⁠
⁠    database='YOUR_DATABASE',
⁠
⁠    schema='YOUR_SCHEMA'
⁠
⁠)

Create a cursor object

cur = conn.cursor()
⁠
⁠try:
⁠
⁠    # Execute a query
⁠
⁠    cur.execute('SELECT * FROM your_table LIMIT 10')
⁠
⁠    # Fetch the results
⁠
⁠    results = cur.fetchall()
⁠
⁠    # Process results
⁠
⁠    for row in results:
⁠
⁠        print(row)
⁠
⁠finally:
⁠
⁠    # Close the cursor and connection
⁠
⁠    cur.close()
⁠
⁠    conn.close()

Always remember to handle your connections and resources properly to maintain security and efficiency.

Nick Barth

Product Engineer

Nick has been interested in data science ever since he recorded all his poops in spreadsheet, and found that on average, he pooped 1.41 times per day. When he isn't coding, or writing content, he spends his time enjoying various leisurely pursuits.

Follow Nick on LinkedIn and GitHub

That’s it, time to try Deepnote

Get started – it’s free
Book a demo

Footer

Solutions

  • Notebook
  • Data apps
  • Machine learning
  • Data teams

Product

Company

Comparisons

Resources

  • Privacy
  • Terms

© Deepnote