Skip to main content
 首页 » 编程设计

Python数据框值插入到数据库表列

2024年12月31日7lyhabc

是否可以将 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 来实现。

首先,您需要创建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

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