简体   繁体   English

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

[英]Python dataframe value insertion to database table column

Is it possible to insert python dataframe values to database table column? 是否可以将python数据框值插入数据库表列?

I am using snowflake as my database. 我正在使用雪花作为数据库。

CommuteTime is the table which contains the StudentID column. CommuteTime是包含StudentID列的表。 "add_col" is the python dataframe. “ add_col”是python数据框。 I need to insert the df values to StudentID column. 我需要将df值插入StudentID列。

Below is my code which i have tried to insert df values to table column. 以下是我尝试将df值插入表列的代码。

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

When I execute the above its not accepting the dataframe. 当我执行上述操作时,它不接受数据帧。 Its throwing the below error. 它抛出以下错误。

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)

Please provide suggestions to fix this.. 请提供解决此问题的建议。

You cannot make it with pd.read_sql_query . 您无法使用pd.read_sql_query做到这pd.read_sql_query

First, you need to create Snowflake cursor . 首先,您需要创建Snowflake cursor

eg 例如

import snowflake.connector

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

Once you have a cursor, you can query like this: cursor.execute("SELECT * from "CommuteTime") 一旦有了游标,就可以像这样查询: cursor.execute("SELECT * from "CommuteTime")

To insert data into tables, you need to use INSERT INTO from Snowflake 要将数据插入表中,您需要使用Snowflake中的INSERT INTO

Please provide more info about your dataframe, to help you further. 请提供有关数据框的更多信息,以帮助您进一步。

I was only able to do that using SQL Alchemy , not Snowflake Python Connector. 我只能使用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)

See here to learn how to establish a connection to Snowflake by passing username , password , account , and table location . 请参阅此处以了解如何通过传递usernamepasswordaccounttable location来建立与Snowflake的连接。

Explore here to learn about the arguments you can pass as if_exists to the function to_sql() . 在这里探索以了解您可以将if_exists传递给函数to_sql()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM