我在使用 MySQLdb 库时遇到问题。我正在尝试将值插入到我的表中,但 MySQL 没有显示它们。更奇怪的是,当我使用命令提示符手动插入值时,主键发生了变化。
举个例子:
'786', '2011-02-16 14:52:38', NULL
'787', '2011-02-16 14:52:52', NULL
'792', '2011-02-16 14:53:25', NULL
我在 786 和 787(主键)处手动插入一些值,然后运行我的 python 脚本,在获得 4 个值后停止它。我输入“SELECT * from table”,但没有看到任何变化。然后我插入另一个值(手动),它显示一个新的主键“792”。似乎 python 脚本正在删除东西......
这是我的 python 代码:
try:
conn = MySQLdb.connect(host = "127.0.0.1",
user = "root",
passwd = "eBao1234",
db = "test")
cursor = conn.cursor()
print 'data base connected'
try:
while 1:
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
i = i + 1
aRead = ser.readline()
aSplit = aRead.split(",")
if aSplit[0] == "t":
print str(i) + ", " + localtime + ", " + aSplit[1]
tableName = "sampdb"
dbquery = "INSERT INTO %s (timestamp, tempReading) VALUES (NOW(), %s);" % (tableName, aSplit[1])
cursor.execute(dbquery)
except KeyboardInterrupt:
ser.close()
#csvResults.close()
#cursor.close()
#conn.close()
print "\nInterrupted."
raw_input("Press enter to exit.")
except Exception,e:
print str(e)
print 'error connecting to database'
cursor.close()
conn.close()
最佳答案
打开自动提交或提交您的更改,请参阅:My data disappeared!
关于Python+MySQLdb怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5018303/