【发布时间】:2011-12-27 05:23:32
【问题描述】:
我正在使用远程数据库将数据导入我的 Django proyect 的数据库。
在MySQLdb 的帮助下,我轻松地创建了如下导入函数:
def connect_and_get_data(useful_string):
CONNECTION = MySQLdb.connect(host=..., port=...,
user=..., passwd=..., db=...,
cursorclass=MySQLdb.cursors.DictCursor,
charset = "utf8")
cursor = CONNECTION.cursor()
cursor.execute("SELECT ... FROM ... WHERE ... AND some_field=%s", (useful_string))
result = cursor.fetchall()
cursor.close()
对此非常满意,按预期工作。
但是继续编写代码,我注意到有时我需要再次连接到数据库,以便执行其他不同的查询。
对我来说,第一个想法很合乎逻辑:
对于我需要的每个查询,定义一个以给定查询作为参数调用connect_and_get_data 的函数......像这样:
def get_data_about_first_amazing_topic(useful_string):
query = "SELECT ... FROM ... WHERE ... AND some_field=%s" %(useful_string)
connect_and_get_data(query)
...
def get_data_about_second_amazing_topic(other_useful_string):
query = "SELECT ... FROM ... WHERE ... AND some_field=%s" %(other_useful_string)
connect_and_get_data(query)
...
对connect_and_get_data进行此修改:
def connect_and_get_data(query):
...
cursor.execute(query)
...
正如您已经想象的那样,这个解决方案失败了。
阅读mluebke对问题python mysql fetch query的回答
“您正在将参数传递给执行函数,而不是进行 python 字符串替换”
我立刻明白我错在哪里;但我仍然觉得缺少一些东西:我尝试了不同的解决方案,但我绝对对所有这些都不满意。
有没有一种“好的”方法来封装我的connect_and_get_data(query) 函数,以便按照我想要的方式为我服务,或者我完全走错了路?
在这种情况下,哪些被认为是“最佳实践”?
【问题讨论】:
标签: python mysql django mysql-python