python - 使用 MySQLdb 执行 INSERT 查询但表为空

标签 python mysql mysql-python

我写了一个 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/

相关文章:

java - JPA OneToOne 发现所有卡在循环中

python - pytest mysql 数据库 fixture : cannot create database

Python、MySQLdb、多个顺序语句(先选择,然后插入)

python - 错误 1064 (4200) - 当我在 MySQL 中输入 GRANT ALL 请求时

python - 使用 python 通过串行发送十六进制

php - 来自远程文件的 SQL 注入(inject)

python - 在 Folium 中突出显示一个特定国家

php - PDO PHP __construct() 警告?

Python 3-截肽正则表达式?

python - 在 Python 中使用 os.walk