【发布时间】:2012-08-22 12:17:25
【问题描述】:
您好,我使用python 和数据库Mysql,现在我想从 python 连接到 Mysql 数据库,我编写了以下代码
方法_1
import MySQLdb as mdb
conn = mdb.connect('ip_address', 'user_name', 'pass_word', 'database_name')
通过使用上面我可以成功连接到 Mysql,但我想知道我们是否可以通过使用连接字符串并像下面提到的那样访问来做同样的事情
方法_2
connectString=Server=ip_address;Database=database_name;UID=user_name;PWD=pass_word
conn = mdb.connect(connectString)
但是我在上面使用时遇到了一个错误,所以任何人都可以让我知道我们是否只能通过 method_1 访问 Mysql 数据库,或者有什么方法可以将访问凭据声明为某个变量并使用我在 method_2
中提到的要连接的变量编辑代码:
实际上我正在尝试的内容如下所示
example_file.ini
[for_primary]
connectString=host="192.168.xx.xxx",user="username_1",passwd="password_1",db="database_1"
[for_secondary]
connectString=host="192.168.xx.xxx",user="username_2",passwd="password_2",db="database_2"
file.py:
import ConfigParser
import MySQLdb as mdb
configFeed = ConfigParser.ConfigParser()
configFeed.read('path to file/example_file.ini')
connectString = configFeed.get('for_primary', 'connectString')
conn = mdb.connect(connectString)
print conn
结果:
File "/usr/lib64/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2005, 'Unknown MySQL server host \'host="192.168.xx.xxx",user="username_1", passwd="password_1",db="database_1"\' (0)')
所以我正在尝试这种方式,因为我需要根据example_file.ini 文件中的选择连接到两个数据库。通过声明访问.ini 文件中的另一个变量的凭据,有什么方法可以像上面那样做。如果我从.ini 文件中获取连接字符串,我期待在这里,它会将这些字符串作为string。
【问题讨论】: