Why isn#39;t the #39;insert#39; function adding rows using MySQLdb?(为什么“插入函数不使用 MySQLdb 添加行?)
问题描述
我正在尝试弄清楚如何在 Python 中使用 MySQLdb 库(我对他们两个都是新手).
I'm trying to figure out how to use the MySQLdb library in Python (I am novice at best for both of them).
我正在关注这里的代码,具体来说:
I'm following the code here, specifically:
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS animal")
cursor.execute ("""
CREATE TABLE animal
(
name CHAR(40),
category CHAR(40)
)
""")
cursor.execute ("""
INSERT INTO animal (name, category)
VALUES
('snake', 'reptile'),
('frog', 'amphibian'),
('tuna', 'fish'),
('racoon', 'mammal')
""")
print "Number of rows inserted: %d" % cursor.rowcount
cursor.close ()
conn.close ()
我可以更改此代码来创建或删除表,但我无法让它实际提交 INSERT
.它按预期返回 row.count
值(即使我更改表中的值,它也会更改为我期望的值).
I can change this code to create or drop tables, but I can't get it to actually commit the INSERT
. It returns the row.count
value as expected (even when I change the value in the table, it changes to what I expect it to be).
每次我用 PHPMyAdmin 查看数据库时,都没有插入.如何将 INSERT
提交到数据库?
Every time I look into the database with PHPMyAdmin there are no inserts made. How do I commit the INSERT
to the database?
推荐答案
你忘记了 commit
数据更改,默认禁用自动提交:
You forget commit
data changes, autocommit is disabled by default:
cursor.close ()
conn.commit ()
conn.close ()
引用 Writing MySQL Scripts with Python DB-API 文档:
"连接对象 commit() 方法提交任何未完成的更改在当前事务中使它们永久存在于数据库中.在DB-API,连接以禁用自动提交模式开始,因此您必须在断开连接之前调用 commit(),否则更改可能会丢失."
"The connection object commit() method commits any outstanding changes in the current transaction to make them permanent in the database. In DB-API, connections begin with autocommit mode disabled, so you must call commit() before disconnecting or changes may be lost."
这篇关于为什么“插入"函数不使用 MySQLdb 添加行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么“插入"函数不使用 MySQLdb 添加行?


- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01