2011-05-22 41 views
4

我在从python插入记录到MySQL数据库时遇到问题。这就是我正在做的。从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语句。

关于我可能做错什么的建议?

+0

后输出 – virtualeyes 2011-05-22 18:02:31

+0

没有输出。 – David 2011-05-22 18:26:24

+0

不好意思?你是否说打印insertStmt(不是查询执行的输出)导致没有输出? – virtualeyes 2011-05-22 18:32:35

回答

9

您尚未提交交易。

conn.commit() 

(该MySQLdb的库设置autocommit为False连接到MySQL时,这意味着你需要手动调用commit或您的修改将不会让它到数据库中。)这里的insertstmt变量

+0

谢谢。这工作。 – David 2011-05-22 20:53:28