簡體   English   中英

Python數據框值插入到數據庫表列

[英]Python dataframe value insertion to database table column

是否可以將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做到這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")

要將數據插入表中,您需要使用Snowflake中的INSERT INTO

請提供有關數據框的更多信息,以幫助您進一步。

我只能使用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)

請參閱此處以了解如何通過傳遞usernamepasswordaccounttable location來建立與Snowflake的連接。

在這里探索以了解您可以將if_exists傳遞給函數to_sql()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM