繁体   English   中英

从Python插入MySQL数据库的问题

[英]Problem with inserting into MySQL database from Python

我无法从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语句。

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

您尚未提交交易。

conn.commit()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM