derpy
derpy

Reputation: 67

Python MySQLdb substituting strings into mysql conn

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)')

Upvotes: 0

Views: 54

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599590

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")

Upvotes: 4

Related Questions