【问题标题】:Python dataframe value insertion to database table columnPython数据框值插入到数据库表列
【发布时间】:2018-08-06 07:04:52
【问题描述】:

是否可以将 python 数据框值插入数据库表列?

我使用雪花作为我的数据库。

CommuteTime 是包含 StudentID 列的表。 “add_col”是 python 数据框。我需要将 df 值插入 StudentID 列。

以下是我尝试将 df 值插入表列的代码。

c_col = pd.read_sql_query('insert into "SIS_WIDE"."PUBLIC"."CommuteTime" ("StudentID") VALUES ("add_col")', engine)

当我执行上述操作时,它不接受数据框。它抛出以下错误。

ProgrammingError: (snowflake.connector.errors.ProgrammingError) 000904 (42000): SQL compilation error: error line 1 at position 68
invalid identifier '"add_col"' [SQL: 'insert into "SIS_WIDE"."PUBLIC"."CommuteTime" ("StudentID") VALUES ("add_col")'] 
(Background on this error at: http://sqlalche.me/e/f405)

请提供解决此问题的建议..

【问题讨论】:

  • 当然不能使用pd.read_sql_query。那是为了从 SELECT 语句的结果创建一个数据框。数据帧上有一个to_sql 方法,但这会(尝试)将数据帧作为表格插入。如果您真的想按照查询建议将整个数据框作为单个属性插入到单个记录中,则必须手动执行此操作。

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


【解决方案1】:

您无法使用pd.read_sql_query

首先,您需要创建Snowflake cursor

例如

import snowflake.connector

cursor = snowflake.connector.connect(
user='username',
password='password',
database='database_name',
schema='PUBLIC',
warehouse='warehouse_name'
).cursor()

一旦有了游标,就可以这样查询:cursor.execute("SELECT * from "CommuteTime")

要向表中插入数据,需要使用INSERT INTO from Snowflake

请提供有关您的数据框的更多信息,以进一步帮助您。

【讨论】:

    【解决方案2】:

    我只能使用 SQL Alchemy 来做到这一点,而不是 Snowflake Python 连接器。

    from sqlalchemy import create_engine
    
    # Establish the connection to the Snowflake database
    sf = 'snowflake://{}:{}@{}{}'.format(user, password, account, table_location)
    engine = create_engine(sf)
    # Write your data frame to a table in database 
    add_col.to_sql(table_name, con=engine, if_exists='replace', index=False)
    

    请参阅here,了解如何通过传递usernamepasswordaccounttable location 来建立与雪花的连接。

    探索here,了解您可以作为if_exists 传递给函数to_sql() 的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 2020-08-15
      相关资源
      最近更新 更多