【发布时间】:2009-09-07 04:37:21
【问题描述】:
我在使用 MySQL 或 Python 时遇到了问题,似乎无法找出问题所在。 INSERTs 似乎只在脚本的最后运行,并没有存储在数据库中。
我有这个脚本:
import MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="example")
dbcursor = db.cursor()
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'before: '+str(temp)
dbcursor.execute('INSERT INTO tablename (data1, data2, data3) VALUES ("1", "a", "b")')
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'after: '+str(temp)
第一次运行时,我得到了预期的输出:
>>>
before: ()
after: ((1L, 'a', 'b'),)
问题是,如果我再次运行它,before 应该已经有条目并且之后不会中断(数据 1 是主键)时会显示为空。
>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
如果我尝试在同一个脚本中运行两次插入命令,它将中断(“主键的重复条目”)
知道这里会发生什么吗?
【问题讨论】: