将vars传递给mysql.connector.connect

时间:2014-11-14 05:50:08

标签: python mysql mysql-connector mysql-connector-python

在python中,我试图将变量传递给connect方法,如下所示,

cnx = mysql.connector.connect(user="%s", password="%s",host="%s",database="%s") % (dbuser,dbpassword,dbhost,dbdatabase) (port is missing)

将值传递给这种方法的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

您可以创建字典并按unpacking it提供关键字参数:

params = {
    'user': dbuser, 
    'password': dbpassword,
    'host': dbhost,
    'database': dbdatabase
}

cnx = mysql.connector.connect(**params)

答案 1 :(得分:1)

你可以直接传递它们:

cnx = mysql.connector.connect(user=dbuser, password=dbpassword, host=dbhost, database=dbdatabase)