我使用pandas df.to_-sql创建了一个sqlite数据库,但是访问它似乎比仅仅读取500mbcsv文件慢得多。
我需要:
使用df.to-sql方法为每个表设置主键
告诉sqlite数据库我的
3.数据帧是?-我能传递像[整数,整数,文本,文本]这样的列表吗?
代码….(格式化代码按钮不工作)

if ext == ".csv":
df = pd.read_csv("/Users/data/" +filename)
columns = df.columns columns = [i.replace(' ', '_') for i in columns]

df.columns = columns
df.to_sql(name,con,flavor='sqlite',schema=None,if_exists='replace',index=True,index_label=None, chunksize=None, dtype=None)

最佳答案

不幸的是,目前无法在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的有限经验中,我发现在创建表后无法添加主键,无法执行更新插入或升迁,以及更新联接导致了许多挫折和一些非常规的解决方法。
最后,在pandas df.to_sql()方法中,有一个dtype关键字参数,可以采用列名字典:types。ie:dtype=col_1:text_

10-06 16:21
查看更多