从Python插入MySQL数据库的问题

4

我在使用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变量的输出。 - virtualeyes
对不起?你是说打印insertStmt(而不是查询exec的输出)没有结果吗? - virtualeyes
如果是这样,那么stringlist可能是罪魁祸首;你能打印一下stringlist吗?如果你不是Python专家,你可能想在Python标签下发布,对于有经验的Python用户来说,这可能是一个简单问题(如果您是有经验的Python用户,请原谅!) - virtualeyes
et voilà, @Dan,经验丰富的Python用户来拯救了。 - virtualeyes
当我运行上述代码时,我没有得到任何输出或错误。 - David
1个回答

9

您尚未提交事务。

conn.commit()

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接