pandas mysql主键_python – 如何使用df.to_sql将pandas数据帧写入sqlite数据库表时设置主键...
不幸的是,现在无法在pandas df.to_sql()方法中设置主键.另外,为了使事情变得更加困难,在创建表之后,无法在sqlite中的列上设置主键.但是,目前的解决方法是使用pandas df.to_sql()方法在sqlite中创建表.然后,您可以创建一个重复的表并设置主键,然后复制数据.然后放下旧桌子进行清理.这将是一个类似的事情.import pandas as pdimport sql
不幸的是,现在无法在pandas df.to_sql()方法中设置主键.另外,为了使事情变得更加困难,在创建表之后,无法在sqlite中的列上设置主键.
但是,目前的解决方法是使用pandas df.to_sql()方法在sqlite中创建表.然后,您可以创建一个重复的表并设置主键,然后复制数据.然后放下旧桌子进行清理.
这将是一个类似的事情.
import pandas as pd
import sqlite3
df = pd.read_csv("/Users/data/" +filename)
columns = df.columns columns = [i.replace(' ', '_') for i in columns]
#write the pandas dataframe to a sqlite table
df.columns = columns
df.to_sql(name,con,flavor='sqlite',schema=None,if_exists='replace',index=True,index_label=None, chunksize=None, dtype=None)
#connect to the database
conn = sqlite3.connect('database')
c = conn.curser()
c.executescript('''
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
ALTER TABLE table RENAME TO old_table;
/*create a new table with the same column names and types while
defining a primary key for the desired column*/
CREATE TABLE new_table (col_1 TEXT PRIMARY KEY NOT NULL,
col_2 TEXT);
INSERT INTO new_table SELECT * FROM old_table;
DROP TABLE old_table;
COMMIT TRANSACTION;
PRAGMA foreign_keys=on;''')
#close out the connection
c.close()
conn.close()
在过去,我已经这样做了,因为我遇到了这个问题.把整个东西包装成一个功能,使它更方便……
在我对sqlite的有限经验中,我发现在创建表后无法添加主键,无法执行Update Inserts或UPSERTS,UPDATE JOIN引起了很多挫折和一些非传统的解决方法.
最后,在pandas df.to_sql()方法中有一个dtype关键字参数,它可以获取列名称的字典:types. IE:dtype = {col_1:TEXT}
更多推荐




所有评论(0)