将可变数量的列导入SQLite数据库

时间:2013-09-23 12:34:38

标签: import sqlite

我有csv文件格式的同义词列表:word,meaning1,meaning2,meaning3....

不同的单词具有不同数量的同义词,这意味着行可能具有可变数量的列。我试图将csv文件导入sqlite数据库,如下所示:

    sqlite3 synonyms
    sqlite> create table list(word text, meaning0 text, meaning1 text, meaning2 text, meaning3 text, meaning4 text, meaning5 text, meaning6 text, meaning7 text, meaning8 text, meaning9 text);
sqlite> .mode list
sqlite> .separator ,
sqlite> .import ./csv/synonyms.csv list 

为了安全起见,我假设最大值。每个单词的10列数。对于少于10个同义词的单词,其他列应为null。执行import命令时出现的错误是:

Error: ./csv/synonyms.csv line 1: expected 11 columns of data but found 3  

我的问题:
1.如果列数少于10,我如何告诉SQLitenull替换它? 2.有没有一种方法可以指定我想要10个字后的字而不是自动输入?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

  • 将所有数据导入单列;
  • 更新表格将列内容拆分为其他列。

样品:

-- Create a table with only one column;
CREATE TABLE table_name(first);
-- Choose a separator which doesn't exist within file
.separator ~
-- Import data
.import file.csv table_name

-- Add another column to split data
ALTER TABLE table_name ADD COLUMN second;
-- Split data between first and second column
UPDATE table_name SET first=SUBSTR(first, 1, INSTR(first, ",")-1), second=SUBSTR(first, INSTR(first, ",")+1) WHERE INSTR(first, ",")>0;

-- Repeat to next column
ALTER TABLE table_name ADD COLUMN third;
-- Split data between second and third column
UPDATE table_name SET second=SUBSTR(second, 1, INSTR(second, ",")-1), third=SUBSTR(second, INSTR(second, ",")+1) WHERE INSTR(second, ",")>0;

-- And so on...
ALTER TABLE table_name ADD COLUMN fourth;
UPDATE table_name SET third=SUBSTR(third, 1, INSTR(third, ",")-1), fourth=SUBSTR(third, INSTR(third, ",")+1) WHERE INSTR(third, ",")>0;

-- Many times as needed...

不是最佳方法,性能应该足够快地呈现它。