gpt4 book ai didi

python - 从文本文件中读取查询参数

转载 作者:行者123 更新时间:2023-11-29 14:50:06 24 4
gpt4 key购买 nike

我想将 mysql-connect 的参数存储在文本文件中,但不知道将它们存储在“query.txt”中的最优雅的方式是什么readline() 命令似乎是一个选项,但不知何故使事情变得非常不优雅。有人可以建议一个顺利的解决方案吗?谢谢!

open("query.txt")
??? read parameters host, user, pass, db from query.txt ???
???sql = MySQLdb.connect (host = "%s", user = "%s", passwd = "%s", db = "s%"), host, user, pass, db)‬

这句话也让我头疼。我还没弄清楚如何正确地进行这个查询......

最佳答案

还有另一种方式:假设您有一个文本文件 params.txt,其中包含具有参数的 Python 样式字典文字。它可能看起来像这样:

# my cool SQL parameters{ "user":   "lilu",  "passwd": "multipass",  "host":   "woo.foo.baz",  "db":     "human-resources" }

You can use a safe and standard Python literals parser ast.literal_eval to convert the contents of this file into a dictionary object, which you can then pass on to your SQL connection function.

import ast

defaults = dict(host='default-host-name', user='default-user-name')

# "U" mode is used so that no matter what newline styles you have in the file,
# they all become \n in memory.
with open('params.txt', 'rU') as params_fo:
params = dict(defaults)
params.update(ast.literal_eval(params_fo.read()))
sql = MySQLdb.connect(**params)

关于python - 从文本文件中读取查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5942959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com