使用mysql-python执行不同的查询
我正在处理一个远程数据库,目的是把数据导入到我的Django项目的数据库中。
在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
“你传递给execute函数的是参数,而不是进行Python字符串替换”
我立刻明白了我的错误所在;但我仍然觉得缺少了什么:我尝试了不同的解决方案,但对它们都不太满意。
有没有一种“好的”方法来封装我的connect_and_get_data(query)
函数,以便能按我想要的方式使用,还是我完全走错了方向?
在这种情况下,哪些方法被认为是“最佳实践”?
2 个回答
0
我正在做一个用Python和MYSQL的网页应用项目,遇到了同样的错误:
MySQLdb._exceptions.OperationalError: (1045, "用户 'root'@'localhost' 被拒绝访问(使用密码:是)").
我所做的就是把应用配置里的密码改成了空字符串 ""
,具体如下:
app.config['MYSQL_PASSWORD'] = ""
然后我成功登录了。
7
我觉得这就是你想要的内容。
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"))
...
不过,如果你打算快速进行多个查询,最好重复使用你的连接,因为频繁建立连接会浪费时间。
...
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()
...
这样可以让你的代码运行得更快。