I have column names in string , now to update table in mysql in the following code :
cursor.execute("""update websites SET %s = %s where weblink = %s""",(key,value,x))
gives error:
_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 ''blog' = 1 where weblink = 'http://blogspot.com/'' at line 1")
key,value = 'blog',2
in cursor.execute key is string and sql table columns are without string , how to solve this problem
Traceback (most recent call last):
File "pgrank.py", line 28, in <module>
cursor.execute("""update websites SET %s = %s where weblink = %s""",(key,value,x))
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_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 '\'blog\'' = 1 where weblink = 'http://blogspot.com/' at line 1')
The "inherent" replacing works fine for data, but not for table names.
In SET %s = %s, the first %s gets replaced by 'blog' while it should be blog or even `blog`.
You should do
cursor.execute("""update websites SET `%s` = %%s where weblink = %%s""" % key, (value,x))
because these are two distinct technologies.
Better readability would be provided by
cursor.execute("update websites SET `" + key +
"` = %s where weblink = %s", (value,x))
and safety is increased if you check if key contains the ` character.
Related
I have had this MySQL error for quite some time now. I cant seem to understand why it keeps occurring, I have imported my database file with all the right information to make the connection but for some reason the error still occurs. I have similar functionality scattered all over my project and I have never got this error, it is literally word for word copying and yet I still get this error. If someone could point me in the right direction it would be much appreciated as I have had no luck online.
Thanks.
Code:
def membership_reactivation(self):
connection.connect(user="root", password="")
email = self.EmailBox.get()
password = self.PasswordBox.get()
query = "UPDATE users SET Status = 'ACTIVE' WHERE Email = %s AND Password = %s;"
cursor.execute(query, (email, password,))
result = cursor.fetchall()
if result:
connection.commit()
connection.close()
self.controller.show_frame("ThankYou")
else:
print("Credentials Not Found in Database.")
connection.close()
Error Message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\AJE\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\AJE\PycharmProjects\ReactivateMembership.py", line 58, in membership_reactivation
result = cursor.fetchall()
File "C:\Users\AJE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mysql\connector\cursor.py", line 1002, in fetchall
raise errors.InterfaceError("No result set to fetch from.")
mysql.connector.errors.InterfaceError: No result set to fetch from.
I got this error when I execute my query
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in de
faulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')
I read this question, this one and this one and this one
I read the Doc and I know that I got this error because image_name in my query is too large
You can also get these errors if you send a query to the server that
is too large.
I set a limite for the length of my variable
image_name = (image_name[:180]) if len(image_name) > 180 else image_name
cmd = "UPDATE `banners` SET `checked` = '1',`local_dir` = %s , `image_name` = %s WHERE `unique_id` = %s "
cursor.execute(cmd,[local_addr,image_name,unique_id])
And I set also max_allowed_packet in /etc/my.cnf
[mysqld]
max_allowed_packet=16M
Do you have any idea how can I avoid this error?
I am trying to load csv data into a mysql table in python:
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost', user='xuanyue', passwd='txn-data', db='eversafe_ml_dev')
cursor = mydb.cursor()
csv_data = csv.reader(file('txns.csv'))
for row in csv_data:
cursor.execute("INSERT INTO txn(UserID, AccountID, TransactionDate, Amount, Description, SimpleDescription, TransactionState, TransactionType, CategoryID, AcctCategoryID, CheckNum, City)"
"VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", row)
mydb.commit()
cursor.close()
The output is:
File "load_data.py", line 10, in <module>
"VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", row)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_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 'ription, TransactionState, TransactionType, CategoryID, AcctCategoryID, CheckNum' at line 1")
I don't understand in my csv file, are the data fields all strings even if it contains transaction date, amount and etc.?
Or should I use numbers, datetime and etc in VALUES( )?
I am trying to add a url to a text row in mysql using python and the MySQLdb library, but when I run my code it says there is an error in my sql syntax. Can you tell me what im doing wrong?
Here is my code:
import MySQLdb as mdb
connection = mdb.connect("Localhost", "root", "", "db")
cursor = connection.cursor()
url = mdb.escape_string("http://www.google.com")
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))
Here is the error:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
self.run()
File "E:\prospector\webworker.py", line 77, in run
cursor.execute("INSERT INTO index(url) VALUES('%s')", (url_t,))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
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 'index(url) VALUES('http://www.google.com/')' at line 1")
I was able to replicate your problem like this:
mysql> create table `index` (url varchar(50));
Query OK, 0 rows affected (0.05 sec)
mysql> insert into index(url) values ('http://www.google.com');
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 'index(url) values ('http://www.google.com')' at line 1
mysql> insert into `index`(url) values ('http://www.google.com');
Query OK, 1 row affected (0.00 sec)
index is a keyword in MySQL. Your life will be easier if you do not use it as a table name.
However, if you really want to, you can use it, but then you have to quote it:
cursor.execute("""INSERT INTO `index`(url) VALUES(%s)""", (url,))
PS: No need to call
url = mdb.escape_string("http://www.google.com")
MySQLdb will do that automatically for you when you call
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))
In fact, since cursor.execute calls mdb.escape_string for you, doing it yourself could cause undesired values to be inserted into the database depending on the value of url:
In [105]: MySQLdb.escape_string("That's all folks")
Out[105]: "That\\'s all folks"
In [106]: MySQLdb.escape_string(MySQLdb.escape_string("That's all folks"))
Out[106]: "That\\\\\\'s all folks"
I have a bug that I don't know how to fix or even reproduce:
query = "SELECT id, name FROM names ORDER BY id"
results = database.execute(query)
where the class Database contains:
def execute(self, query):
cursor = self.db.cursor()
try:
cursor.execute(query)
return cursor.fetchall()
except:
import traceback
traceback.print_exc(file=debugFile)
return []
This is how I open the database connection:
self.db = MySQLdb.connect(
host=mysqlHost,
user=mysqlUser,
passwd=mysqlPasswd,
db=mysqlDB
)
This is the stacktrace of the error:
File "foo.py", line 169, in application results = config.db.execute(query)
File "Database.py", line 52, in execute
return cursor.fetchall()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 340, in fetchall
self._check_executed()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 70, in _check_executed
self.errorhandler(self, ProgrammingError, "execute() first")
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: execute() first
Do you have any ideas of why this is happening and how can I fix it? I searched on the internet and I found out that the reason may be having 2 cursors, but I have only one.
try this in your traceback it's for debugging:
except ProgrammingError as ex:
if cursor:
print "\n".join(cursor.messages)
# You can show only the last error like this.
# print cursor.messages[-1]
else:
print "\n".join(self.db.messages)
# Same here you can also do.
# print self.db.messages[-1]