cyb*_*ron 4 python mysql mysql-python
我用来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)
Run Code Online (Sandbox Code Playgroud)
该表的声明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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
运行该过程后,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');
Run Code Online (Sandbox Code Playgroud)
我可以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 |
+----+------------------------------------------------+------------------------+
Run Code Online (Sandbox Code Playgroud)
请注意,该id值正在递增......这可能意味着数据正在被插入,但没有持久化?有人可以帮我吗?
您可能正在使用事务数据库,在这种情况下您必须调用
self.conn.commit()
Run Code Online (Sandbox Code Playgroud)
(事实上,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()
Run Code Online (Sandbox Code Playgroud)
commit但是,在某些情况下,您可能希望在调用或之前执行多个查询rollback。在这种情况下,您可能希望commit从中删除execute_query并在需要时显式调用,或者在退出套件时commit使用上下文管理器进行调用。commitwith
请注意,MySQLdb连接是上下文管理器。你可以写
connection = MySQLdb.connect(
host=config.HOST, user=config.USER,
passwd=config.PASS, db=config.MYDB, )
with connection as cursor:
cursor.execute(...)
Run Code Online (Sandbox Code Playgroud)
并且连接将connection.commit()在退出时with-suite或connection.rollback()出现异常时调用。以下是 MySQLdb.connections.py 中控制此操作的代码:
def __enter__(self): return self.cursor()
def __exit__(self, exc, value, tb):
if exc:
self.rollback()
else:
self.commit()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1942 次 |
| 最近记录: |