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

2024-05-23 14:52:21 发布

您现在位置: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

“向execute函数传递参数,而不是执行python字符串替换”

我很快就明白我错在哪里了;但我仍然觉得有些东西不见了:我尝试过不同的解决方案,但我对所有这些都很不满意。

有没有一种“好”的方式来封装我的connect_and_get_data(query)功能,以便按照我想要的方式为我服务,或者我完全走错了这条路?

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


Tags: and函数from数据库executedatagetstring
2条回答

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

MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)").

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

app.config['MYSQL_PASSWORD'] = ""

然后我成功地登录了。

我想这就是你要找的。

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

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

相关问题 更多 >