繁体   English   中英

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

[英]Executing different queries using 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()

对此非常满意,按预期工作。

但是继续编写代码,我注意到有时我需要再次连接到数据库,以便执行其他不同的查询。

第一个想法对我来说非常合乎逻辑:对于我需要的每个查询,定义一个函数,该函数以给定的查询作为参数调用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)函数,以便按照我想要的方式为我服务,或者我完全走错了路?

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

我想这就是你要找的。

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()
...

这将使您的代码执行得更好。

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

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

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

app.config['MYSQL_PASSWORD'] = ""

然后我就登录成功了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM