无法将csv文件中的多行导入sqlite数据库

时间:2011-06-02 17:20:59

标签: sqlite csv

我在尝试将整个csv文件导入sqlite数据库时遇到问题。这些是我的终端命令:

sqlite3 DB.sql
create table table1 (id integer primary key, question VARCHAR(500), Aanswer VARCHAR(255), Banswer VARCHAR(255), Canswer VARCHAR(255), Danswer VARCHAR(255));
.mode csv
.import db.csv table1
select * from table1

和输出:

7,"Who's head did Courtney Cox say was on her body in Scream 2?","Heather Graham",Oprah,"*Jennifer Aniston","Demi Moore"

您会注意到它只会在几个字段周围放置引号,这些字段似乎是随机的...我不知道这是不是为什么它不会继续导入下一行。

谢谢!

编辑:

以下是我的csv文件的前几行:

1,What movie follows Cher and Dionne named after great singers of the past that now do infomercials?,10 Things I Hate About You,Cant Hardly Wait,*Clueless,Freeway
2,What 90s movie did critic Janet Maslin describe as : A gale-force movie with the energy to blow audiences right out of the theater?,Avalanche,Aftershocks,Armageddon,*Twister
3,What actress declined Neve Campbell's role in Scream?,*Drew Barrymore,Carla Hatley,Courteney Cox,Rose McGowan

如果我在自己中加上引号,就会吐出这样的东西:

"""What was the name of Milla Jovovich's character in the Fifth Element?""","""Billy""","""Fog""","""Mugger""","""*Leeloo"""

2 个答案:

答案 0 :(得分:1)

sqlite的.import命令只能理解LF(0xA)行尾代码,而不能理解CR(0xD)。用十六进制编辑器检查你的输入文件。

答案 1 :(得分:0)

您需要在带有空格的字段周围放置引号。

喜欢这个

C:\Documents and Settings\james\My Documents>type test.csv
1,field_with_no_spaces,'field with spaces'
2,field_with_no_spaces,'field with spaces'
3,field_with_no_spaces,'field with spaces'
4,field_with_no_spaces,'field with spaces'

C:\Documents and Settings\james\My Documents>sqlite3 test.dat
SQLite version 3.6.19
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table t1 (id integer primary key, q1, q2 );
sqlite> .mode csv
sqlite> .import test.csv t1
sqlite> select * from t1;
1,field_with_no_spaces,"'field with spaces'"
2,field_with_no_spaces,"'field with spaces'"
3,field_with_no_spaces,"'field with spaces'"
4,field_with_no_spaces,"'field with spaces'"

您将在带空格的字段周围获得“额外”引号。不是问题。重要的是导入整个文件,对吗?

如果您关心额外的请求,请关闭csv模式,如此

sqlite> .mode list
sqlite> .separator ,
sqlite> select * from t1;
1,field_with_no_spaces,'field with spaces'
2,field_with_no_spaces,'field with spaces'
3,field_with_no_spaces,'field with spaces'
4,field_with_no_spaces,'field with spaces'

在数据周围加上引号,给出

1,What movie follows Cher and Dionne named after great singers of the past that now do infomercials?,10 Things I Hate About You,Cant Hardly Wait,*Clueless,Freeway
2,What 90s movie did critic Janet Maslin describe as : A gale-force movie with the energy to blow audiences right out of the theater?,Avalanche,Aftershocks,Armageddon,*Twister
3,What actress declined Neve Campbell's role in Scream?,*Drew Barrymore,Carla Hatley,Courteney Cox,Rose McGowan