我尝试将 5 个配置文件(rubin1.cfg...rubin5.cfg)导入 sqlite3 数据库。配置文件是明显的字符串列表。每个字符串都以换行符开始。我会将文件字符串导入 sqlite 表并在字段FileID插入配置文件的索引。
import sqlite3, codecs
con = sqlite3.connect("ConfigImport.db")
cur = con.cursor()
n = 0
sql = """\
DROP TABLE IF EXISTS
TblRubin;
CREATE TABLE TblRubin
(StringId INTEGER PRIMARY KEY,
FileId INTEGER
String TEXT)
"""
cur.executescript(sql)
while n < 5:
n = n + 1
i = 0
path = r'C:\\t7\\config\\rubi'+ str(n) + '.cfg'
f = codecs.open(path, "r", encoding='cp1251')
str2 = codecs.open(path, "r", encoding='cp1251').readlines()
print 'File', path, 'opened. Number of strings: ', str(len(str2))
for line in f:
cur.execute('insert into tblrubin values (null, ?, ?)', n, [str2[i].rstrip()])
i = i + 1
con.commit()
cur.close()
con.close()
结果:
File C:\\t7\\config\\rubi1.cfg opened. Number of strings: 6528
Traceback (most recent call last):
File "C:\t7\programs\analysis\ConfigImport.py", line 25, in <module>
cur.execute('insert into tblrubin values (null, ?, ?)', (n, str2[i].rstrip()))
sqlite3.OperationalError: table tblrubin has 2 columns but 3 values were supplied
当我尝试仅导入一个文件并且脚本包含一个参数时,如下所示...:
cur.execute('insert into tblrubin2 values (null, ?)', [str2[i].rstrip()])
...导入插入操作成功。
您能否建议如何使用两个参数制作将文本文件导入到 sqlite db 的正确脚本?