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

查看:53
本文介绍了为什么“插入"功能不使用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 ()

引用使用Python DB-API编写MySQL脚本文档:

连接对象的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天全站免登陆