使用mysql-python执行不同的查询

问题描述 投票:5回答:2

我正在使用远程数据库将数据导入到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的回答

“您正在将参数传递给execute函数,而不是执行python字符串替换”

我立刻明白我哪里错了;但我仍然感到缺少某些东西:我尝试了不同的解决方案,但是我对所有这些解决方案绝对不满意。

是否有一种“ good”方式封装我的connect_and_get_data(query)函数,以便以我想要的方式为我提供服务,否则我完全走错了路?

在这种情况下哪些被认为是“最佳实践”

python mysql django mysql-python
2个回答
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()
...

这将使您的代码性能更好。


0
投票

我正在用Python和MYSQL做一个Web应用程序项目,并且我有相同的错误类型:

MySQLdb._exceptions.OperationalError:(1045,“用户的访问被拒绝'root'@'localhost'(使用密码:是)“)。

我所做的就是将应用程序配置密码更改为空字符串"",如下所示:

app.config['MYSQL_PASSWORD'] = ""

然后我成功登录。

© www.soinside.com 2019 - 2024. All rights reserved.