0

I have a connection line as below and I want to substitute in variables, but cannot get it to work:

db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="database")

I change this to use a variable:

db = MySQLdb.connect(host="localhost", user="%s", passwd="password", db="database") % "root"

Error: mysql_exceptions.OperationalError: (1045, "Access denied for user '%s'@'localhost' (using password: YES)")

So, it is not substituting and tries to run the query with %s. I also tried with a .format (instead of %s) and got the same issue.

To get around this, I was going to substitute the line beforehand and then add in the connection line as one argument, however even a basic version of this doesn't work for me. Here is a trial run, but it fails even without any substituation:

variable = '''MySQLdb.connect(host="localhost", user="root", passwd="password", db="database")''' 
db = MySQLdb.connect(variable)

This results in mysql trying to pass the entire variable as the first argument (the host): _mysql_exceptions.OperationalError: (2005, 'Unknown MySQL server host \'host="localhost", user="root", passwd="password", db="database"\' (2)')

2
  • 1
    While Daniel's answer is definitely correct and to be preferred, the actual mistake you made here is this: You're dealing with 4 strings here (used as keyword arguments). You would need to apply the substitution to the individual string(s) for your approach to work, like this: MySQLdb.connect(host="localhost", user="%s" % "root", passwd="password", db="database-%s" % n) Commented Sep 30, 2015 at 12:32
  • @LukasGraf thanks for the clarification. I had considered that but didn't try it since it looked like something that would throw an error fi I had % "root" in the middle of the command. Guess not. Commented Sep 30, 2015 at 12:39

1 Answer 1

4

I think you're over thinking this. This is a standard function call, and has nothing at all that is specific to MySQLdb. As with any call, if you want to use a variable, you just do so:

user = 'root'
MySQLdb.connect(host="localhost", user=user, passwd="password", db="database")
Sign up to request clarification or add additional context in comments.

Comments

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.