'How to make a prepared statement without explicit quotes in case of string variables
I use MySQLdb
library. When I make a query like this
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = ?", src)
where src is a string variable, I get an error:
TypeError: not all arguments converted during string formatting
I also get an error, if I make it like this:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = %s" % src)
However, I do not have an error in this case:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = '%s'" % src)
But what I do not like about this statement is explicit quotes around %s
. I would like to make the driver decide the type of variable and do it implicitly. Otherwise, in case of automatic queries it would be a real problem to do all this routine of parsing variable types and "preparing" a prepared statement.
EDIT
It seems, as if I found a solution. The right syntax was:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = %s" , (src,))
where the variables (src
) is provided as a tuple.
Solution 1:[1]
'src' in your code means values that you want to pass instead of question mark. If that is true try the below code. Else ignore
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = " + src);
Solution 2:[2]
Then try this
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC like '%" + src + "%'");
Solution 3:[3]
It seems, as if I found a solution. The right syntax was:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = %s" , (src,))
where the variables (src
) is provided as a tuple.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Revathi |
Solution 2 | Revathi |
Solution 3 | faremal |