我在Ubuntu机器上的python中遇到sqlite问题。我运行一些循环,将数据插入sqlite3数据库。第一个循环将两者都插入学生和地址表,最后一个循环只插入地址表。
问题似乎是最后一个循环在第一次运行时不会向db添加超过一两个记录,任何后续运行它都能完美运行。我已经多次尝试删除数据库并运行脚本一次,检查数据,然后再次运行脚本。
我想知道这是否可能是由于我添加到数据库的数据量。
我提供了以下代码的重点:
import sqlite3
conn = sqlite3.connect('data.db')
conn.text_factory = str
for file in directory:
studentNo,surname,Address = getFromFile(file)
conn.execute("INSERT INTO Students (StudentNumber,Surname) VALUES (?,?);", (studentNo,surname));
cursor = conn.execute("SELECT ID from Students WHERE StudentNumber = '" + studentNo + "';")
for row in cursor:
conn.execute("INSERT INTO Addresses (StudentID,Address) VALUES (?, ?);", (row[0], Address));
break
conn.commit()
#insert more stuff through similar loops, each one of these loops runs about 15000 times
# ...
# every other loop except the following appear to work well enough
for file in directory:
studentNo, address = getDataFromAlternativeSource(file)
cursor = conn.execute("SELECT ID from Students WHERE StudentNumber = '" + studentNo + "';")
for row in cursor:
conn.execute("INSERT INTO Addresses (StudentID,Address) VALUES (?, ?);", (row[0], address));
break
conn.commit()
conn.close()
如果需要更多详细信息,请在下面发表评论
答案 0 :(得分:1)
根据您向我们展示的代码,问题很可能是getDataFromAlternativeSource(file)
返回的studentNo
值与您认为的不同 - 并且Students
中没有{} 1}}表。这将导致SELECT
什么都不返回,你的循环永远不会执行 - 一个静默失败模式。
至少没有描述您尝试使用getFromFile()
和getDataFromAlternativeSource()
完成的内容,很难猜出您希望添加到数据库中的内容。
无论如何,用大量数据压倒SQLite是很困难的,当然,几乎任何现有文件系统都可以在每个文件一个记录的基础上生成相对少量的记录。
答案 1 :(得分:-1)
你有"地址"和"地址"没问题好吗?
我不知道插页的含义,但您可以尝试这样做:
try:
with con:
con.execute("INSERT INTO Addresses (StudentID,Address) VALUES (?, ?);", (row[0], Address))
except sqlite3.IntegrityError:
print "couldn't add the same address twice"
如果地址已经在数据库中,则插入语句不会产生任何结果。