为什么“插入"函数不使用 MySQLdb 添加行? [英] Why isn't the 'insert' function adding rows using MySQLdb?

查看:35
本文介绍了为什么“插入"函数不使用 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 添加行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆