MySQL插入的数据不存储在正确的数据库中,只是临时的吗?
我在使用MySQL或Python时遇到了一些麻烦,似乎无法找到问题所在。INSERT
操作似乎只在脚本运行期间有效,数据并没有真正存储到数据库里。
我有一个这样的脚本:
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
的结果是空的,应该已经有数据在里面,而after
也没有出错(数据1是主键)。
>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
如果我在同一个脚本中尝试运行插入命令两次,它会出错(“主键重复”)。
你觉得这可能是什么原因呢?