Kent Ellingson
Kent Ellingson

Reputation: 35

Pandas Dataframes with the Snowflake Python Connector

trying to get a data query to work with Snowflake using their connector.

import snowflake.connector as sf
import pandas as pd
import sys

ctx = sf.connect(
    user='<user>',
    password='<password>',
    account='<account>',
    warehouse='<warehouse?',
    database='<db>',
    schema='<schema>',
    )
cs = ctx.cursor()

try:
    cs.execute('select TOP 5 fish, price from fishtable order by fish;')
except Exception as error:
    error = sys.exc_info()[0]
    message = sys.exc_info()[1]
    print(f"Error: {error}\nMessage: {message}")
finally:
    ctx.close()
    
print(cs.rowcount)
print(cs.sfqid)
df = cs.fetch_pandas_all()   #could not get this to work
df

print(cs.rowcount) shows the correct total of 5.

Using sfqid in snowflake console returns the query results as expected.

But no data in DF...

Upvotes: 2

Views: 1586

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175706

Assignment should be done before closing/disposing connection:

try:
    cs.execute('select TOP 5 fish, price from fishtable order by fish;')
    df = cs.fetch_pandas_all() 
except Exception as error:
    error = sys.exc_info()[0]
    message = sys.exc_info()[1]
    print(f"Error: {error}\nMessage: {message}")
finally:
    ctx.close()

df

Upvotes: 4

Related Questions