【问题标题】:Python MySQLdb cursor.lastrowidPython MySQLdb cursor.lastrowid
【发布时间】:2017-03-01 13:45:42
【问题描述】:

我在使用 MySQLdb python 库从 MySQL 数据库返回自动递增的 ID 列时遇到问题。 我有类似的东西:

sql = """INSERT INTO %s (%s) VALUES (\"%s\")""" %(tbl, colsf, valsf)
try:
    cursor.execute(sql)
    id = cursor.lastrowid
    db.close()
except:
    print "Failed to add to MySQL database: \n%s" %sql
    print sys.exc_info()
    db.close()
    exit()

但是 lastrowid 命令似乎返回了不正确的值。例如,我尝试从 MySQL 命令行打印出各种 id 列,这些列显示它们为空,但每次运行 python 脚本时 lastrowid 值都会增加 1。有什么想法吗?

【问题讨论】:

    标签: python mysql python-2.7 mysql-python


    【解决方案1】:

    原来这些值没有正确提交到 MySQL 数据库,添加“db.commit()”命令似乎可以解决问题。

    sql = """INSERT INTO %s (%s) VALUES (\"%s\")""" %(tbl, colsf, valsf)
    try:
        cursor.execute(sql)
        id = cursor.lastrowid
        cursor.close()
        db.commit() 
        db.close()
    except:
        print "Failed to add to MySQL database: \n%s" %sql
        print sys.exc_info()
        db.close()
        exit()
    

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 2010-11-10
      • 2012-12-04
      • 2011-11-10
      • 2011-11-14
      相关资源
      最近更新 更多