Search code examples
pythondatabase-connectionpymysql

Python DB-Connection via string


I'm searching the Internet for about an hour or so, but can't find a solution for my problem:

I'm trying to set up a Database connection. If I open the connection like this everything works fine:

db = pymysql.connect(host='127.0.0.1', user='python', db='test')

But if i want to set up the connection via string I get an error:

db_file = str("host='127.0.0.1', user='python', db='test'")
db = pymysql.connect(db_file)

Errormessage:

pymysql.err.OperationalError: (2003, 'Can\'t connect to MySQL server on "host=\'127.0.0.1\', user=\'python\', db=\'test\'" ([Errno -2] Name or service not known)')

I hope anybody can help me out by telling me how to set up the database connection via string(or something else predefineable)


Solution

  • You are passing a single string as parameter to the function pymysql.connect(), but it expects 3 parameters at least: host, user, db.

    So the string db_file gets loaded as the first parameter (host), nothing gets in the other two, generating the error.

    The correct way is something like this:

    host = '127.0.0.1',
    user ='python' 
    db ='test'
    db_conn = pymysql.connect(host, user, db)
    

    UPDATE:

    if you want to use a connection file directly try using Option Files:

    https://dev.mysql.com/doc/connector-python/en/connector-python-option-files.html