python - MySQL INSERT 数据没有存储在正确的数据库中,只是临时存储的?

标签 python 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'),)

如果我尝试在同一个脚本中运行两次插入命令,它将中断(“主键的重复条目”)

知道这里会发生什么吗?

最佳答案

您没有提交交易。

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

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

Reference

关于python - MySQL INSERT 数据没有存储在正确的数据库中,只是临时存储的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1387573/

相关文章:

php - 使用 PhP 连接到 HTML 的 MySQL 表

.net - 有没有人设法使用 Iron Python 安装 Python 模块?

python - 正则表达式从字符串python中提取三个字符

python - 在 healpy 中对 HEALPix map 应用旋转

java - 使用 INNER JOIN 查询

mysql - SELECT 查询不传递参数

mysql - 使用参数在 bash 中执行 .sql 文件

Mysql手动自增并发连接数证明

python - 如何打印具有相似字符串的值?

python - 消除 JSON 文档中键值的前导和尾随反冲