Hi, I am using python and a database like Mysql . Now I want to connect to the Mysql database from python, and I wrote the code below
method_1
import MySQLdb as mdb conn = mdb.connect('ip_address', 'user_name', 'pass_word', 'database_name')
Using the above, I can successfully connect to Mysql, but I want to know if we can do the same with the connection and access string, as I mentioned below
Method_2
connectString=Server=ip_address;Database=database_name;UID=user_name;PWD=pass_word conn = mdb.connect(connectString)
But I get the error using the above, so that someone can tell me if we can access the Mysql database only with method_1 , or is there a way to declare the access credentials of some variable and use this variable to connect, as I mentioned in method_2
Edited Code:
In fact, what I'm trying to give below
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
Result:
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)')
So I try this way because I need to connect to two databases depending on the choice in the example_file.ini file. Is there a way to do it like abobe by declaring access to the credentials of another variable in the .ini file. I expect here if I get a connection string from a .ini file that accepts them as string .