gpt4 book ai didi

python - 数据被插入到 MySQL 但不是永久的 - Python

转载 作者:可可西里 更新时间:2023-11-01 07:59:05 26 4
gpt4 key购买 nike

我正在使用 MySQLdb 来操作一个 MySQL 数据库,我有下面的例程,将一些数据注入(inject)到一个名为 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

dbconnDbconn类的一个对象,定义为:

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');

我可以通过命令行将其手动注入(inject) 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 值正在递增...这可能意味着数据正在插入,但没有持久化?有人可以帮我吗?

最佳答案

您可能正在使用事务数据库,在这种情况下您必须调用

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()

但是,在调用 commitrollback 之前,您可能希望执行多个查询。在这种情况下,您可能希望从 execute_query 中删除 commit 并在需要时显式调用 commit,或者使用上下文管理器调用 当您退出 with 套件时提交


请注意,MySQLdb 连接是上下文管理器。你可以写

connection = MySQLdb.connect(
host=config.HOST, user=config.USER,
passwd=config.PASS, db=config.MYDB, )

with connection as cursor:
cursor.execute(...)

并且连接将在退出 with-suite 时调用 connection.commit(),或者 connection.rollback() 如果有一个异常(exception)。这是在 MySQLdb.connections.py 中控制它的代码:

def __enter__(self): return self.cursor()

def __exit__(self, exc, value, tb):
if exc:
self.rollback()
else:
self.commit()

关于python - 数据被插入到 MySQL 但不是永久的 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18477124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com