【问题标题】:MySQL INSERT data does not get stored in proper db, only temporary?MySQL INSERT 数据没有存储在正确的数据库中,只是临时的?
【发布时间】:2009-09-07 04:37:21
【问题描述】:

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

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

>>> 
before: ()
after: ((1L, 'a', 'b'),)

问题是,如果我再次运行它,before 应该已经有条目并且之后不会中断(数据 1 是主键)时会显示为空。

>>> 
before: ()
after: ((1L, 'a', 'b'),)
>>> 
before: ()
after: ((1L, 'a', 'b'),)
>>> 
before: ()
after: ((1L, 'a', 'b'),)

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

知道这里会发生什么吗?

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    您没有提交交易。

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

    Reference

    【讨论】:

    • 如果它不在数据库中,为什么第二个选择返回该值?这是事务性数据库和非事务性数据库的区别吗?
    • @joaoc 第二个选择返回值,因为 INSERT 的结果对您自己的会话可见,但在您提交之前对其他人不可见
    【解决方案2】:

    我觉得你需要打电话

    db.commit()

    【讨论】:

    • 在每个 dbcursor.execute 之后还是最后只执行一次?
    【解决方案3】:

    问题是您没有提交更改。它可以通过 conn.commit()

    阅读更多here

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 2012-03-29
      相关资源
      最近更新 更多