问题
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 ()
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).
Every time I look into the database with PHPMyAdmin there are no inserts made. How do I commit the INSERT
to the database?
回答1:
You forget commit
data changes, autocommit is disabled by default:
cursor.close ()
conn.commit ()
conn.close ()
Quoting Writing MySQL Scripts with Python DB-API documentation:
"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."
来源:https://stackoverflow.com/questions/9173073/why-isnt-the-insert-function-adding-rows-using-mysqldb