MySQL INSERT数据不会存储在正确的数据库中,只是暂时的?

gre*_*eye 2 python mysql

我遇到了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)
Run Code Online (Sandbox Code Playgroud)

我第一次运行它时得到了预期的输出:

>>> 
before: ()
after: ((1L, 'a', 'b'),)
Run Code Online (Sandbox Code Playgroud)

问题是,如果我再次运行它,before当它应该已经有条目并且after不会中断(数据1是主键)时出现空.

>>> 
before: ()
after: ((1L, 'a', 'b'),)
>>> 
before: ()
after: ((1L, 'a', 'b'),)
>>> 
before: ()
after: ((1L, 'a', 'b'),)
Run Code Online (Sandbox Code Playgroud)

如果我尝试在同一个脚本中运行insert命令两次,它将会中断("PRIMARY KEY的重复项")

知道这里可能会发生什么吗?

OMG*_*ies 9

您没有提交交易.

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

cursor.execute(...)
conn.commit()
Run Code Online (Sandbox Code Playgroud)

参考