无法使用Python的MYSQLdb modu向DB添加行

2024-04-28 05:35:20 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的生活,我不明白为什么下面的模块不会添加新行到我的数据库。我可以使用命令行界面添加它们。我也可以使用其他方法添加它们(例如,将命令写入脚本文件并使用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()

Tags: 脚本idexecutedblibrarynotthiscursor
2条回答

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

来自MySQLdb的FAQ

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.

您可以调用db.autocommit(True)来打开连接的自动提交,或者只要在您认为必要时手动调用db.commit()。你知道吗

相关问题 更多 >