MySQL插入的数据不存储在正确的数据库中,只是临时的吗?

3 投票
3 回答
2898 浏览
提问于 2025-04-15 14:07

我在使用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'),)

如果我在同一个脚本中尝试运行插入命令两次,它会出错(“主键重复”)。

你觉得这可能是什么原因呢?

3 个回答

2

问题是你没有提交更改。你可以通过执行 conn.commit() 来完成这个操作。

想了解更多,可以点击 这里

3

我觉得你需要调用一下

db.commit()

10

你没有提交事务。

conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor()

cursor.execute(...)
conn.commit()

参考链接

撰写回答