I've been trying to work out where I've been going for most of the day, and still can't work it out, been staring at it too long and I'm sqill very early in my learning of Python & MySQL.
The query I've built is:
query = "UPDATE `db`.`%s" % table + "` SET %s" % table + "`.`%s" % field + "` = `%s" % daychangeperc + "` WHERE (`db`.`%s" % table + "`.`id` = %s" % rowid +") LIMIT 1;"
The error I'm getting is:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.DayChange= '-0.00736251627767' WHERE (outofthe_finance.test1.id` = 1) ' at line 1")
Anyone able to point out where I'm going wrong? I'm sure it's probably obvious for many.
Thanks in advance.
That's pretty messy, perhaps try doing it like this instead:
query = """UPDATE db.%s SET %s.%s = %s WHERE db.%s.id = %s LIMIT 1""" % (table,table,field,daychangeperc,table,rowid)
First, here is your query re-written so that all of the arguments for your format string come at the end:
query = "UPDATE `db`.`%s` SET %s`.`%s` = `%s` WHERE (`db`.`%s`.`id` = %s) LIMIT 1;" \
%(table,table,field,daychangeperc,table,rowid)
When you look at it this way, you can see that after the SET keyword you have some unbalanced back-ticks. I think this is the issue, and is hard to see because of how you wrote your string.
Related
I have been trying to make this part of my A-Level project where I have a database in MyPHPAdmin and my code grabs a value, compares it to a preset value and if it is unchanged, uses that location in the database to store a new value. (I cant just insert new data due to other parts of my code). I have been trying to use a variable with a value stored in it from an input box, however it refuses to take the value. I have tried lots of things and I cant seem to get it to work and I seem to get a different error everytime I try something different. I fear it may just be something simple I am missing, but for the life of me I cant figure it out and it is driving me insane. (Also yes I have looked at the documentation but it is not of much use for my situation)
My Code:
mycursor = database.cursor(buffered=True)
mycursor.execute("SELECT name FROM creationPokemon")
myresult = mycursor.fetchone()[0]
print(myresult)
if myresult == "Placeholder1":
sql = ("UPDATE creationPokemon SET name = %s WHERE name = %s")
val = ('Placeholder1', cName)
else:
myresult = mycursor.fetchone()[0]
print(myresult)
mycursor.execute(sql)
database.commit()
The error I have landed on this time is:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s WHERE name = %s' at line 1
Any help is much appreciated.
python and mysql connector need at least 2 dimemsns when you use tuples and you need to fill both placeholders
mycursor = database.cursor(buffered=True)
mycursor.execute("SELECT name FROM creationPokemon")
myresult = mycursor.fetchone()[0]
print(myresult)
if myresult == "Placeholder1":
sql = "UPDATE creationPokemon SET name = %s WHERE name = %s"
val = (cName,cName)
mycursor.execute(sql,val)
database.commit()
else:
myresult = mycursor.fetchone()[0]
print(myresult)
Upon running this script:
#! /usr/bin/env python
import MySQLdb as mdb
import sys
class Test:
def check(self, search):
try:
con = mdb.connect('localhost', 'root', 'password', 'recordsdb');
cur = con.cursor()
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
ver = cur.fetchone()
print "Output : %s " % ver
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
test = Test()
test.check("test")
I get an error of:
./lookup
Traceback (most recent call last):
File "./lookup", line 27, in <module>
test.check("test")
File "./lookup", line 11, in creep
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
I have zero idea why. I'm trying to do parameterized querys, but it's been nothing but a pain. I'm somewhat new to Python, so it's probably an obvious problem.
Instead of this:
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
Try this:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )
See the MySQLdb documentation. The reasoning is that execute's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).
You can try this code:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
You can see the documentation
'%' keyword is so dangerous because it major cause of 'SQL INJECTION ATTACK'.
So you just using this code.
cursor.execute("select * from table where example=%s", (example,))
or
t = (example,)
cursor.execute("select * from table where example=%s", t)
if you want to try insert into table, try this.
name = 'ksg'
age = 19
sex = 'male'
t = (name, age, sex)
cursor.execute("insert into table values(%s,%d,%s)", t)
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
I do not why, but this works for me . rather than use '%s'.
The accepted answer by #kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.
There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported
cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')
but the 1.2.5 versions require
cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])
as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.
The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.
If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:
$ pip install MySQL-python==1.2.3
I don't understand the first two answers. I think they must be version-dependent. I cannot reproduce them on MySQLdb 1.2.3, which comes with Ubuntu 14.04LTS. Let's try them. First, we verify that MySQL doesn't accept double-apostrophes:
mysql> select * from methods limit 1;
+----------+--------------------+------------+
| MethodID | MethodDescription | MethodLink |
+----------+--------------------+------------+
| 32 | Autonomous Sensing | NULL |
+----------+--------------------+------------+
1 row in set (0.01 sec)
mysql> select * from methods where MethodID = ''32'';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9999'' ' at line 1
Nope. Let's try the example that Mandatory posted using the query constructor inside /usr/lib/python2.7/dist-packages/MySQLdb/cursors.py where I opened "con" as a connection to my database.
>>> search = "test"
>>> "SELECT * FROM records WHERE email LIKE '%s'" % con.literal(search)
"SELECT * FROM records WHERE email LIKE ''test''"
>>>
Nope, the double apostrophes cause it to fail. Let's try Mike Graham's first comment, where he suggests leaving off the apostrophes quoting the %s:
>>> "SELECT * FROM records WHERE email LIKE %s" % con.literal(search)
"SELECT * FROM records WHERE email LIKE 'test'"
>>>
Yep, that will work, but Mike's second comment and the documentation says that the argument to execute (processed by con.literal) must be a tuple (search,) or a list [search]. You can try them, but you'll find no difference from the output above.
The best answer is ksg97031's.
According PEP8,I prefer to execute SQL in this way:
cur = con.cursor()
# There is no need to add single-quota to the surrounding of `%s`,
# because the MySQLdb precompile the sql according to the scheme type
# of each argument in the arguments list.
sql = "SELECT * FROM records WHERE email LIKE %s;"
args = [search, ]
cur.execute(sql, args)
In this way, you will recognize that the second argument args of execute method must be a list of arguments.
May this helps you.
I encountered this error while executing
SELECT * FROM table;
I traced the error to cursor.py line 195.
if args is not None:
if isinstance(args, dict):
nargs = {}
for key, item in args.items():
if isinstance(key, unicode):
key = key.encode(db.encoding)
nargs[key] = db.literal(item)
args = nargs
else:
args = tuple(map(db.literal, args))
try:
query = query % args
except TypeError as m:
raise ProgrammingError(str(m))
Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.
I keep getting a error with a SQL query that is written in python.
Here is the code in question:
else:
else_query = "SELECT count(*) FROM PARKING_SPOTS WHERE OCCUPANCY = %s"
cursor.execute(else_query, (occupancy,)
" AND WHERE LOCATION = %s", (location,))
Here's the error message:
File "exp1", line 116
" AND WHERE LOCATION = %s", (location,))
^
SyntaxError: invalid syntax
Can anyone spot the error ? I've changed things around several times, including containing part of the SQL query in a variable, yet I receive the same error.
your query is incorrect because you can't have 2 WHERE clauses
you can only pass one querystring
so make that:
else_query = """SELECT count(*) FROM PARKING_SPOTS WHERE OCCUPANCY = %s
AND LOCATION = %s
"""
cursor.execute(else_query, (occupancy, location))
parameters for the query need to be passed as a tuple
Upon running this script:
#! /usr/bin/env python
import MySQLdb as mdb
import sys
class Test:
def check(self, search):
try:
con = mdb.connect('localhost', 'root', 'password', 'recordsdb');
cur = con.cursor()
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
ver = cur.fetchone()
print "Output : %s " % ver
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
test = Test()
test.check("test")
I get an error of:
./lookup
Traceback (most recent call last):
File "./lookup", line 27, in <module>
test.check("test")
File "./lookup", line 11, in creep
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
I have zero idea why. I'm trying to do parameterized querys, but it's been nothing but a pain. I'm somewhat new to Python, so it's probably an obvious problem.
Instead of this:
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
Try this:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )
See the MySQLdb documentation. The reasoning is that execute's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).
You can try this code:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
You can see the documentation
'%' keyword is so dangerous because it major cause of 'SQL INJECTION ATTACK'.
So you just using this code.
cursor.execute("select * from table where example=%s", (example,))
or
t = (example,)
cursor.execute("select * from table where example=%s", t)
if you want to try insert into table, try this.
name = 'ksg'
age = 19
sex = 'male'
t = (name, age, sex)
cursor.execute("insert into table values(%s,%d,%s)", t)
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
I do not why, but this works for me . rather than use '%s'.
The accepted answer by #kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.
There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported
cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')
but the 1.2.5 versions require
cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])
as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.
The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.
If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:
$ pip install MySQL-python==1.2.3
I don't understand the first two answers. I think they must be version-dependent. I cannot reproduce them on MySQLdb 1.2.3, which comes with Ubuntu 14.04LTS. Let's try them. First, we verify that MySQL doesn't accept double-apostrophes:
mysql> select * from methods limit 1;
+----------+--------------------+------------+
| MethodID | MethodDescription | MethodLink |
+----------+--------------------+------------+
| 32 | Autonomous Sensing | NULL |
+----------+--------------------+------------+
1 row in set (0.01 sec)
mysql> select * from methods where MethodID = ''32'';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9999'' ' at line 1
Nope. Let's try the example that Mandatory posted using the query constructor inside /usr/lib/python2.7/dist-packages/MySQLdb/cursors.py where I opened "con" as a connection to my database.
>>> search = "test"
>>> "SELECT * FROM records WHERE email LIKE '%s'" % con.literal(search)
"SELECT * FROM records WHERE email LIKE ''test''"
>>>
Nope, the double apostrophes cause it to fail. Let's try Mike Graham's first comment, where he suggests leaving off the apostrophes quoting the %s:
>>> "SELECT * FROM records WHERE email LIKE %s" % con.literal(search)
"SELECT * FROM records WHERE email LIKE 'test'"
>>>
Yep, that will work, but Mike's second comment and the documentation says that the argument to execute (processed by con.literal) must be a tuple (search,) or a list [search]. You can try them, but you'll find no difference from the output above.
The best answer is ksg97031's.
According PEP8,I prefer to execute SQL in this way:
cur = con.cursor()
# There is no need to add single-quota to the surrounding of `%s`,
# because the MySQLdb precompile the sql according to the scheme type
# of each argument in the arguments list.
sql = "SELECT * FROM records WHERE email LIKE %s;"
args = [search, ]
cur.execute(sql, args)
In this way, you will recognize that the second argument args of execute method must be a list of arguments.
May this helps you.
I encountered this error while executing
SELECT * FROM table;
I traced the error to cursor.py line 195.
if args is not None:
if isinstance(args, dict):
nargs = {}
for key, item in args.items():
if isinstance(key, unicode):
key = key.encode(db.encoding)
nargs[key] = db.literal(item)
args = nargs
else:
args = tuple(map(db.literal, args))
try:
query = query % args
except TypeError as m:
raise ProgrammingError(str(m))
Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.
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.
'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);
Then try this
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC like '%" + src + "%'");
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.