【问题标题】:AttributeError: 'SnowflakeCursor' object has no attribute 'cursor'AttributeError:“SnowflakeCursor”对象没有属性“光标”
【发布时间】:2021-02-06 20:18:43
【问题描述】:

我正在尝试使用 to_sql 方法将我的 DataFrame 写入 Snowflake。

sf_conn = snowflake.connector.connect(
    account=*****,
    user=*****,
    password=*****,
    role=*****,
    warehouse=*****,
    database=*****
    
)

sf_cur = sf_conn.cursor()
df = pd.DataFrame([('Mark', 10), ('Luke', 20)], columns=['name', 'balance'])
df.to_sql('TEST3',con=sf_cur, schema='public', index=False)

但还没有运气。

File "/home/karma/.local/lib/python3.6/site-packages/pandas/io/sql.py", line 1584, in execute
    cur = self.con.cursor()
AttributeError: 'SnowflakeCursor' object has no attribute 'cursor'

甚至尝试给con=sf_conn,但得到以下错误:

pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting

我可以使用 sqlAlchemy create_engine lib 完成相同的工作,但我想专门使用雪花连接。

【问题讨论】:

    标签: python pandas snowflake-cloud-data-platform


    【解决方案1】:

    在使用 pandas.DataFrame.to_sql 和 Snowflake 时,您需要使用 SQLAlchemy 引擎作为连接。

    当您使用df.to_sql 时,您需要传入 SQLAlchemy 引擎,而不是标准 Snowflake 连接对象(也不是您尝试做的游标)。您需要使用 pip 安装 snowflake-sqlalchemy,但您不需要安装 snowflake-connector-python,因为 snowflake-sqlalchemy 会为您执行此操作。

    这是一个对我有用的例子:

    from sqlalchemy import create_engine
    import os
    import pandas as pd
    
    snowflake_username = os.environ['SNOWFLAKE_USERNAME']
    snowflake_password = os.environ['SNOWFLAKE_PASSWORD']
    snowflake_account = os.environ['SNOWFLAKE_ACCOUNT']
    snowflake_warehouse = os.environ['SNOWFLAKE_WAREHOUSE']
    snowflake_database = 'test_db'
    snowflake_schema = 'public'
    
    
    if __name__ == '__main__':
        engine = create_engine(
            'snowflake://{user}:{password}@{account}/{db}/{schema}?warehouse={warehouse}'.format(
                user=snowflake_username,
                password=snowflake_password,
                account=snowflake_account,
                db=snowflake_database,
                schema=snowflake_schema,
                warehouse=snowflake_warehouse,
            )
        )
        df = pd.DataFrame([('Mark', 10), ('Luke', 20)], columns=['name', 'balance'])
        df.to_sql('TEST_TABLE', con=engine, schema='public', index=False, if_exists='append')
    

    每次我运行上述脚本时,Mark 和 Luke 记录都会附加到我的 test_db.public.test_table 表中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 2019-03-17
      • 2020-03-25
      • 2019-07-25
      • 1970-01-01
      • 2012-12-01
      • 2021-04-19
      相关资源
      最近更新 更多