问题是我无法从文本文件中获取数据以写入数据库 文本文件逐行排列:
John Doe 012-345-6789
正如您所看到的,我已经拆分了文本并将所有类别理顺了
但是不断收到像InterfaceError: Error binding parameter 0 - probably un supported type
这样的错误或者将47个条目写入一个字段的错误。
非常感谢你。
import sqlite3
conn = sqlite3.connect('phoneNumbers.db')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS People ')
cur.execute('CREATE TABLE People (firstname TEXT, lastname TEXT, phonenumber TEXT)')
########
file = open('phoneNumbers.txt', 'r')
try:
file = open('phoneNumbers.txt', 'r')
except:
print "File not found"
data = file.read()
data = data.split()
for line in data:
first = data[0::3]
last = data [1::3]
num = data [2::3]
cur.execute('INSERT INTO People (firstname, lastname, phonenumber) VALUES (?, ?, ?)', (first, last, num))
conn.commit()
cur.execute('SELECT firstname, lastname, phonenumber FROM People')
for row in cur:
print row
conn.close()
答案 0 :(得分:2)
您的代码存在一些问题:
file
作为您的文件,这是一个内置名称,您应该重命名 first
,last
和num
是列表,execute
不能将列表用作参数。
有一个executeMany
但在这种情况下我不喜欢它。
修改强>
甚至更流畅的是逐行读取并使用with
命令。
with open('phoneNumbers.txt', 'r') as f:
for line in f:
data = line.split()
cur.execute('INSERT INTO People (firstname, lastname, phonenumber) VALUES (?, ?, ?)', (data[0], data[1], data[2]))
if 'str' in line:
break
<强>原始强>
我会使用带有index
的for,然后像这样在循环中执行INSERT。
try:
numbersFile = open('phoneNumbers.txt', 'r')
except:
print "File not found"
data = numbersFile.read()
data = data.split()
for i in range(0, len(data), 3):
first = data[i]
last = data[i+1]
num = data[i+2]
cur.execute('INSERT INTO People (firstname, lastname, phonenumber) VALUES (?, ?, ?)', (first, last, num))
conn.commit()