Python数据帧值插入数据库表列

问题描述 投票:2回答:2

是否可以将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)

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

python sql snowflake
2个回答
0
投票

你不能用pd.read_sql_query制作它。

首先,你需要创建Snowflake cursor

EG

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

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


0
投票

我只能使用SQL Alchemy,而不是Snowflake Python Connector。

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建立与Snowflake的连接。

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

© www.soinside.com 2019 - 2024. All rights reserved.