我写了一个 Python 脚本来执行一些查询,如下所示:
cur.execute('CREATE DATABASE IF NOT EXISTS testdb;')
table = """CREATE TABLE IF NOT EXISTS links (
keyword VARCHAR(30) NOT NULL,
url VARCHAR(30) NOT NULL)"""
cur.execute(table)
从 MySQL shell 我看到没有任何问题:
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| testdb |
+--------------------+
4 rows in set (0.02 sec)
mysql> SHOW TABLES;
+--------------------+
| Tables_in_testdb |
+--------------------+
| links |
+--------------------+
1 row in set (0.00 sec)
问题是一个带有两个参数的 INSERT
查询:
cur3.execute("INSERT INTO links(keyword,url) VALUES(%s,%s);",(sys.argv[1],link))
检查MySQL有问题:
mysql> SELECT * from links;
Empty set (0.00 sec)
为什么执行INSERT
查询后表为空?
最佳答案
确保使用 Connection.commit
提交您的更改:
cur3.execute("INSERT INTO links(keyword, url) VALUES(%s, %s)", (sys.argv[1], link))
connection_object.commit()
根据 MySQLdb FAQ - My data disappeared! (or won't go away!) :
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.
关于python - 使用 MySQLdb 执行 INSERT 查询但表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27426257/