0

对于我的生活,我无法弄清楚为什么下面的模块不会向我的数据库添加新行。我可以使用命令行界面添加它们。我也可以使用其他方式添加它们(即,将命令写入脚本文件并使用os.system('...'),但如果我使用cursor.execute(),则不会添加任何行(即使创建了表)。这是一个最小的脚本,供您查看乐趣。注意运行此脚本时没有收到任何错误或警告

#!/usr/bin/env python

import MySQLdb

if __name__ == '__main__':
   db = MySQLdb.connect ( host="localhost", user="user", passwd="passwd", db="db" )
   cursor = db.cursor()

   cursor.execute ( 
   """
      CREATE TABLE IF NOT EXISTS god_i_really_hate_this_stupid_library
      (
         id            INT NOT NULL auto_increment,
         username      VARCHAR(32) NOT NULL UNIQUE,
         PRIMARY KEY(id)
      ) engine=innodb;
   """
   )

   cursor.execute ( 
   """
      INSERT INTO god_i_really_hate_this_stupid_library
      ( username )
      VALUES
      ( 'Booberry' );
   """
   )

   cursor.close()
4

2 回答 2

2

您需要调用commit您的连接,否则所做的所有更改都将自动回滚。

于 2012-05-28T21:07:01.650 回答
2

来自MySQLdb的常见问题解答:

Starting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you'll need to do connection.commit() before closing the connection, or else none of your changes will be written to the database.

Conversely, you can also use connection.rollback() to throw away any changes you've made since the last commit.

Important note: Some SQL statements -- specifically DDL statements like CREATE TABLE -- are non-transactional, so they can't be rolled back, and they cause pending transactions to commit.

You can call db.autocommit(True) to turn autocommit on for the connection or just call db.commit() manually whenever you deem it necessary.

于 2012-05-28T21:11:37.727 回答