1

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)

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for the quick reply. I try to adapt an older routine where I had an sqlite3 database-file (there the name db_file comes from) to simply writing all my stuff into a database server. I really don't want to rewrite all this old coding and replacing the parameters everywhere. Therefore I tried to set up the connection with one single parameter.
I suggest you to adapt your codebase to the new method, but if you want to pass a file i suggest you try using option files: dev.mysql.com/doc/refman/8.0/en/option-files.html
0

You can't pass a string in for multiple arguments like that, you would have to assign each argument to it's own variable like this;

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

3 Comments

Hi, thanks but that doesn't do the trick for me (see the comment I put under m.rp's answer.
Unfortunately you do have to define them individually, although once they're defined once you can reuse those variables across the whole code base.
I feared I had to swallow this bitter pill :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.