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 Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
