Search code examples
pythonpython-3.xinsertsnowflake-cloud-data-platform

Unable to insert data into Snowflake table using Python Connector


Previously I have tried using the COPY INTO command for loading data into Snowflake. Now I am trying to insert the data line by line but I am facing issue in executing the insert query.

insert into SUPERHERO values('Spider-Man (Peter Parker)', 'Secret Identity', 'Good Characters', 'Hazel Eyes', 'Brown Hair', 'Male', 'Living', 4043.0, 'Aug-62', 1962.0);

The insert query is working fine in the Snowflake console but not executing in Python.

Sample function code:

def insert_data(name, id, align, eye, hair, sex, alive, appearances, first_appearance, year):
    try:
        snowconn = snowflake.connector.connect(
            user='<username>', password='<password>', account='<locator>'
        )
        snowcursor = snowconn.cursor()  # session snowflake connection created
    except:
        return 'Error in connecting'
    try:
        # Use ROLE for accessing database and other items
        db_query = "use role {snowrole};".format(snowrole='ACCOUNTADMIN')
        snowcursor.execute(db_query)
        # USE DATABASE STATEMENT
        db_query = "use database {snowDB};".format(snowDB='DATA_INGESTION')
        snowcursor.execute(db_query)
        # USE SCHEMA EXECUTION
        db_query = "use schema {snowSCH};".format(snowSCH="INGESTION_SCH")
        snowcursor.execute(db_query)
    except:
        return 'error in roles/db/schema.'
    try:
        print(name, id, align, eye, hair, sex, alive, appearances, first_appearance[0], year)
        db_query = ("insert into SUPERHERO values('Spider-Man (Peter Parker)', 'Secret Identity', 'Good Characters', 'Hazel Eyes', 'Brown Hair', 'Male', 'Living', 4043.0, 'Aug-62', 1962.0);")
        snowcursor.execute(db_query)
        return 'success'
    except:
        return 'error in inserting data'

Here is the output that I am getting.

enter image description here

Previously I have tried using the COPY INTO command for loading data into Snowflake. Now I am trying to insert the data line by line but I am facing issue in executing the insert query. Even though the insert is working fine in the Snowflake console. I am unable to insert data using Python. I expected this to work and the data to be inserted.


Solution

  • Warehouse was not being used in this code so failure in execution.

    db_query = "use warehouse {snowWH};".format(snowWH="NEW_WH")
    snowcursor.execute(db_query)
    

    Issue is resolved now.