将文本文件内容传输到数据库python中

时间:2014-02-18 18:26:50

标签: python database sqlite

我对python / sqlite有点新意。我试图将纺织品的内容转移到数据库中。纺织品的格式如下:

hello hello hello
hello hello hello hello hello
hello hello hello hello

我将纺织品解析成2d列表,每行作为自己的元组,即[hello,hello,hello]。我想将这个列表转移到一个数据库中,其中每个元素都是一个属性,每个元组都是它自己的行 - 有一些空白属性,因为每一行的长度都不同。

我保留错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied

我不确定为什么会这样。我以为我用query_string变量解决了这个问题。如果有人能帮助我,那就太好了。我的代码如下:

import sqlite3

ins = open( "foo.txt", "r" ) 
parseTable = []

for line in ins:
   row = line.rstrip().split(',') 
   parseTable.append(row)

#print parseTable

conn = sqlite3.connect('sample.db')
c = conn.cursor()

c.execute('''CREATE TABLE sample (Item_0 TEXT, Item_1 TEXT, Item_2 TEXT, Item_3 TEXT, Item_4 TEXT)''')

query_string = 'INSERT INTO sample VALUES (?, ?, ?, ?, ?)'

c.executemany(query_string, parseTable)

conn.commit()

1 个答案:

答案 0 :(得分:1)

您需要添加一些额外的None值来填充行:

for line in ins:
    row = line.split()[:5]
    row.extend([None] * (5 - len(row)))
    parseTable.append(row)

这会将您的示例数据拆分为空格(不是逗号),将行数限制为最多5个元素,如果长度低于,则会添加None个值4个要素。

对于这些行的缺失列,None值会转换为NULL

演示:

>>> import sqlite3
>>> ins = '''\
... hello hello hello
... hello hello hello hello hello
... hello hello hello hello
... '''.splitlines()
>>> parseTable = []
>>> for line in ins:
...     row = line.split()[:5]
...     row.extend([None] * (5 - len(row)))
...     parseTable.append(row)
... 
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('''CREATE TABLE sample (Item_0 TEXT, Item_1 TEXT, Item_2 TEXT, Item_3 TEXT, Item_4 TEXT)''')
<sqlite3.Cursor object at 0x1083d8960>
>>> query_string = 'INSERT INTO sample VALUES (?, ?, ?, ?, ?)'
>>> c.executemany(query_string, parseTable)
<sqlite3.Cursor object at 0x1083d8960>
>>> conn.commit()
>>> c.execute('SELECT * FROM sample')
<sqlite3.Cursor object at 0x1083d8960>
>>> for row in c:
...     print row
... 
(u'hello', u'hello', u'hello', None, None)
(u'hello', u'hello', u'hello', u'hello', u'hello')
(u'hello', u'hello', u'hello', u'hello', None)