我正在使用MySQLdb
来操作MySQL
数据库,我有以下例程,在名为urls
的表中注入一些数据:
def insert_urls(dbconn, filenames):
root = "<path>/"
link = "http://<url>/"
for f in filenames:
filename = root + f + ".html"
local_url = link + f + ".html"
print(filename, local_url)
sql = """
INSERT INTO urls(url, filename) VALUES('%s', '%s');
""" % (local_url, filename)
print(sql)
dbconn.execute_query(sql)
urls
表的声明在这里找到:
def create_urls_table():
sql = """
CREATE TABLE IF NOT EXISTS urls (
id INT NOT NULL AUTO_INCREMENT,
url BLOB NOT NULL,
filename BLOB NOT NULL,
PRIMARY KEY(id)
) ENGINE=INNODB;
"""
return sql
dbconn
是类Dbconn
的对象,定义为:
class Dbconn:
def __init__(self,
host="",
user="",
pwd="",
database=""):
self.host = host
self.user = user
self.pwd = pwd
self.db = database
self.cursor = None
self.conn = None
try:
self.conn = MySQLdb.connect(host=self.host,
user=self.user,
passwd =self.pwd,
db=self.db)
self.cursor = self.conn.cursor()
print "Connection established"
except MySQLdb.Error, e:
print "An error has occurred ", e
def execute_query(self, sql=""):
try:
self.cursor.execute(sql)
except MySQLdb.Error, e:
print "An error has occurred ", e
运行程序insert_urls
后,我得到以下输出:
INSERT INTO urls(url, filename) VALUES ('http://<url>/amazon.html','<path>/amazon.html');
INSERT INTO urls(url, filename) VALUES('http://<url>/linkedin.html', '<path>/linkedin.html');
INSERT INTO urls(url, filename) VALUES('http://<url>/nytimes.html', '<path>/nytimes.html');
我可以通过命令行手动注入MySQL
。
但是,在进行SELECT * FROM urls
查询时,我什么也没找到。手动插入两行后,我得到了:
mysql> select * from urls;
+----+------------------------------------------------+------------------------+
| id | url | filename |
+----+------------------------------------------------+------------------------+
| 19 | http://<url>/yelp.html | <path>/yelp.html |
| 29 | http://<url>/amazon.html | <path>/amazon.html |
+----+------------------------------------------------+------------------------+
请注意,id
值正在递增...这可能意味着数据正在插入,但不会持续存在?有人可以帮帮我吗?
答案 0 :(得分:4)
您可能正在使用交易数据库,在这种情况下您必须致电
self.conn.commit()
(实际上,INNODB是一个交易数据库。)
您可以将commit
纳入execute_query
:
def execute_query(self, sql=""):
try:
self.cursor.execute(sql)
except MySQLdb.Error as e:
print "An error has occurred ", e
self.conn.rollback()
else:
self.conn.commit()
但是,在您致电commit
或rollback
之前,您可能希望执行大量查询。在这种情况下,您需要从commit
中删除execute_query
,并在需要时显式调用commit
,或在退出{{1时使用上下文管理器调用commit
}} - 套件
请注意,with
连接是上下文管理器。你可以写
MySQLdb
,如果出现异常,连接会在退出connection = MySQLdb.connect(
host=config.HOST, user=config.USER,
passwd=config.PASS, db=config.MYDB, )
with connection as cursor:
cursor.execute(...)
时调用connection.commit()
,或with-suite
。
以下是在MySQLdb.connections.py中控制它的代码:
connection.rollback()
答案 1 :(得分:1)
在execute()
语句后,请致电commit()
:
self.cursor.execute(sql)
self.conn.commit()
有关详细信息,请参阅:python mysql insert data