[英]Insert a pandas dataframe into a SQLite table
So I have a dataframe imported from excel and an SQL Table with matching columns. 所以我有一个从excel导入的数据框和一个带有匹配列的SQL表。 So far I have been updating the table using the columns as lists:
到目前为止,我一直在使用列作为列表更新表:
Schedule_Frame = DataFrame(Sheet_Schedule)
Column_ID=Schedule_Frame['ID']
Column_list=list(Column_ID)
for i in range(len(Column_list)):
miCursor.execute("UPDATE SCHEDULE SET ID=? WHERE rowid=?",(Column_list[i],i))
However, since what I have in SQLite is a table that matches my dataframe columns, I am sure that there is a way to update the whole SQLite table using my frame. 但是,由于我在SQLite中拥有一个与我的数据框列相匹配的表,因此我确信可以使用我的框架来更新整个SQLite表。
Any ideas how to do it? 有什么想法怎么做?
Thanks a lot!! 非常感谢!!
I think you're using sqlite3
package to access your SQLite database. 我认为您正在使用
sqlite3
软件包访问您的SQLite数据库。 How about using SQLAlchemy – which operates well with Pandas' data structures – to access the database? 如何使用SQLAlchemy (可与Pandas的数据结构配合使用)来访问数据库?
from sqlalchemy import create_engine
engine = create_engine('sqlite:///<replace_this_with_path_to_db_file>', echo=False)
Then doing: 然后做:
Schedule_Frame.to_sql('SCHEDULE', con=engine, if_exists='append')
Edit : Example code 编辑 :示例代码
from sqlalchemy import create_engine
import pandas as pd
engine = sqlalchemy.create_engine('sqlite:///my.db', echo=False)
df = pd.DataFrame([[1,2],[1,2]], columns=['a', 'b'])
df.to_sql('mytable', con=engine, if_exists='append')
In sqlite3 CLI: 在sqlite3 CLI中:
sqlite> select * from 'mytable';
0|1|2
1|1|2
Resources: 资源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.