【问题标题】:Problem with inserting into MySQL database from Python从 Python 插入 MySQL 数据库的问题
【发布时间】:2011-08-30 16:34:57
【问题描述】:

我在从 python 向 MySQL 数据库中插入记录时遇到问题。这就是我正在做的。

def testMain2():
        conn = MySQLdb.connect(charset='utf8', host="localhost", user="root", passwd="root", db="epf")
        cursor = conn.cursor()

        tableName = "test_table"

        columnsDef = "(export_date BIGINT, storefront_id INT, genre_id INT, album_id INT, album_rank INT)"
        exStr = """CREATE TABLE %s %s""" % (tableName, columnsDef)
        cursor.execute(exStr)

        #Escape the record
        values = ["1305104402172", "12", "34", "56", "78"]                    
        values = [conn.literal(aField) for aField in values]

        stringList = "(%s)" % (", ".join(values))
        columns = "(export_date, storefront_id, genre_id, album_id, album_rank)"
        insertStmt = """INSERT INTO %s %s VALUES %s""" % (tableName, columns, stringList)
        cursor.execute(insertStmt)

        cursor.close()
        conn.close()

表已创建,但表中没有任何内容。我可以使用相同的凭据在终端中成功运行INSERT 语句。

关于我可能做错的任何建议?

【问题讨论】:

  • 在此处发布 insertStmt 变量的输出
  • 请问?您是说打印 insertStmt(不是查询 exec 的输出)导致没有输出?
  • 如果是这样,那么 stringlist 可能是罪魁祸首;你能打印字符串列表吗?不是pythonista,你可能想在python标签下发帖,对于有经验的python用户来说,这可能是一个明智的选择(如果是你,请道歉!)
  • 等瞧,@Dan,经验丰富的 python 用户来救援
  • 我在运行上述代码时没有得到任何输出或错误。

标签: python mysql macos terminal


【解决方案1】:

你还没有提交交易。

conn.commit()

(MySQLdb 库在连接 MySQL 时将 autocommit 设置为 False。这意味着您需要手动调用 commit 否则您的更改将永远无法进入数据库。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-09
    • 2021-03-29
    • 2011-08-04
    • 2023-02-05
    • 2016-04-13
    • 1970-01-01
    • 2016-02-05
    • 2014-08-04
    相关资源
    最近更新 更多