【发布时间】:2019-02-22 03:11:41
【问题描述】:
我有两个程序:一个填充和更新数据库,另一个每 10 秒从数据库中选择一次信息。
我使用 Pymysql。
当我更新数据库我提交数据时,我可以用命令行在数据库中看到结果,但是另一个程序有相同的输出并且没有得到新的数据!
除了SELECT之外,我还需要进行特殊查询吗?
我需要在所有查询之前关闭连接并重新打开它吗?
我在启动程序时创建了GetData 类,并且每10 秒调用一次get_data。
class GetData:
def __init__(self):
self.conn = pymysql.connect(host='localhost', user='root', password='', db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
def get_data(self, data):
with self.conn.cursor() as cursor:
self.sql = "SELECT id_data, somedata FROM mytable WHERE (%s = 'example');"
cursor.execute(self.sql, (data,))
return cursor.fetchall()
def close_conn(self):
self.conn.close()
填充数据库的程序:
class FillDb:
def __init__(self):
self.conn = pymysql.connect(host='localhost', user='root', password='', db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
#added this line but doesen't help!
self.conn.autocommit(True)
def add_in_db(self, data):
with self.conn.cursor() as cursor:
self.sql = "INSERT INTO mytable (somedata) VALUES (%s);"
cursor.execute(self.sql, (data,))
self.conn.commit()
【问题讨论】:
-
如果没有看到一些有代表性的代码,我们无法回答这个问题。
-
您不能参数化列名。我不确定
self.sql = "SELECT id_data, somedata FROM mytable WHERE (%s = "example");"会起作用 -
还请向我们展示实例化您的类并调用其方法的代码。我和@roganjosh 在一起,您的 SELECT 查询看起来不对。如果
example应该是字符串文字,则它应该用单引号引起来,而不是在这种情况下用双引号引起来。此外,您似乎在调用fetchall后通过退出上下文管理器已关闭的游标上调用execute;至少基于此处显示的缩进。我希望get_data中的cursor.fetchall会引发异常。 -
有趣,看起来他们真的允许在关闭的游标上调用
fetchall。不过我有一个疑问,如果你使用with self.conn as cursor:而不是with self.conn.cursor() as cursor:会发生什么? -
对如何以及为什么感兴趣?那我会写一个答案;评论太长了。他们的文档没有错,只是……不完整。
标签: python mysql python-3.x mariadb pymysql