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

时间:2011-05-09 21:54:16

标签: python mysql text-files

我想在文本文件中存储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)‬

这条线也让我头疼。我还没想出如何正确地进行这个查询......

5 个答案:

答案 0 :(得分:1)

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

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

您可以使用安全且标准的Python文字解析器ast.literal_eval将此文件的内容转换为字典对象,然后您可以将其传递给SQL连接函数。

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)

答案 1 :(得分:0)

使用序列化会更好,更舒适:

import cPickle

with open('pickler file.pic','w') as f:
    host, user, passw, db = 'bouloudou','bididi',198754,'the_db'
    cPickle.dump([host, user, passw, db],f)



with open('pickler file.pic','r') as f:
    host, user, passw, db = cPickle.load(f)

答案 2 :(得分:0)

假设“query.txt”包含:

hostname username password db  

你可以这样做:

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

答案 3 :(得分:0)

如果您希望文本文件格式良好且易于阅读,则可以使用JSON:

# Query parameters class
class QueryParams:
    def __init__(self, paramsDict):
        self.__dict__.update(paramsDict)

# Read text file
q = json.load(open('query.txt'), object_hook = lambda dc: QueryParams(dc))

# Use params
sql = MySQLdb.connect (host = "%s", user = "%s", passwd = "%s", db = "s%"), q.host, q.user, q.pass, q.db)‬

答案 4 :(得分:0)

parameters.txt包含

MyHost, MyUsername, MyPassword, MyDb

在剧本中:

host, user, passw, db = open('parameters.txt').read().split()
sql = MySQLdb.connect (host , user, passw, db)