dol*_*a33 5 python mysql django mysql-python
我正在使用远程数据库将数据导入我的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()
Run Code Online (Sandbox Code Playgroud)
非常满意,按预期工作.
但继续使用代码,我注意到有时我需要再次连接到数据库,以便执行其他不同的查询.
对我来说,第一个想法是非常符合逻辑的:对于我需要的每个查询,定义一个函数,该函数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)
...
Run Code Online (Sandbox Code Playgroud)
通过以下修改connect_and_get_data:
def connect_and_get_data(query):
...
cursor.execute(query)
...
Run Code Online (Sandbox Code Playgroud)
正如您可能想象的那样,此解决方案失败了.
阅读mluebke对python mysql fetch查询问题的回答
"您正在将参数传递给execute函数,而不是执行python字符串替换"
我立刻明白我错了; 但我仍然觉得缺少了一些东西:我尝试了不同的解决方案,但我对所有这些解决方案都非常不满意.
是否有一种"好"的方式来封装我的connect_and_get_data(query)功能,为了按照我想要的方式为我服务,或者我完全走错了路?
在这种情况下哪些被认为是"最佳做法"?
我想这就是你要找的东西.
def connect_and_get_data(query, data):
...
cursor.execute(query, data)
...
def get_data_about_first_amazing_topic(useful_string):
query = "SELECT ... FROM ... WHERE ... AND some_field=%s"
connect_and_get_data(query, ("one","two","three"))
...
Run Code Online (Sandbox Code Playgroud)
但是,如果您要快速进行多次查询,最好重复使用您的连接,因为连接太多会浪费时间.
...
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", ("first", "amazing", "topic"))
first_result = cursor.fetchall()
cursor.execute("SELECT ... FROM ... WHERE ... AND some_field=%s", (("first", "amazing", "topic")))
second_result = cursor.fetchall()
cursor.close()
...
Run Code Online (Sandbox Code Playgroud)
这将使您的代码执行得更好.