pu369com

如何使用Python和Pandas处理SQLite数据库

代码:

import sqlite3
import pandas as pd

conn = sqlite3.connect('database.db')

data = {'A':['x','y','z'],'B':[1000,2000,3000],'C':[10,20,30]}
df = pd.DataFrame(data,index=['a','b','c'])
#将df写入sqlite3
df.to_sql('table_name', conn, if_exists='replace', index=False)
#再向数据库中追加一行
cursor = conn.cursor()   #c即一个游标对象
cursor.execute("INSERT INTO table_name ('A','B','C') VALUES ('zz',40,'cc')")
#读取sqlite3到df1
df1 = pd.read_sql_query("SELECT * from table_name", conn)
print(df1)
#如果数据量太大,应该直接用sql语句来读取若干行
query = 'SELECT * FROM table_name order by C limit 1000 offset 1'
get  = cursor.execute(query).fetchall()
print(get)

 

 

参考:https://blog.csdn.net/devid008/article/details/130986820

https://www.jianshu.com/p/875f8d7b7903

https://zhuanlan.zhihu.com/p/645562185

https://www.cnblogs.com/zongfa/p/11332274.html

posted on 2023-10-13 16:18  pu369com  阅读(260)  评论(0编辑  收藏  举报

导航