我在使用 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'),)
如果我尝试在同一个脚本中运行两次插入命令,它将中断(“主键的重复条目”)
知道这里会发生什么吗?
最佳答案
您没有提交交易。
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor()
cursor.execute(...)
conn.commit()
关于python - MySQL INSERT 数据没有存储在正确的数据库中,只是临时存储的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1387573/