Flask-Mysql Python 1064 error when update table into Mysql - python

Been stuck whole day with this update mysql table error while build a web app with Flask python.
(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 'WHERE 'user_id'='28'' at line 1")
Tried removing comma and adding `` according to solution of similar problems in Stackoverflow but it's not working.
#app.route('/update')
def update():
try:
conn = mysql.connect()
update = conn.cursor(pymysql.cursors.DictCursor)
sql = "UPDATE user SET user_photo=%s, WHERE user_id=%s"
_path="User.30.1.jpg"
_id="28"
data = (_path,_id)
update.execute(sql,data)
conn.commit()
return render_template('training.html')
except Exception as e:
print(e)

Remove the comma from the sql variable:
sql = "UPDATE user SET user_photo=%s WHERE user_id=%s"

Related

ProgrammingError 1064 doing CREATE TABLE AS SELECT from an existing table with MySQL in Python

I have an existing table in the cloud and I want to make a copy of it. I connect to my database via pymysql, extract the username from an input provided from the new user, and I want to create a new table that will be called by the username, and that table will be a copy of the original one. When I run the code below, I have the following error:
pymysql.err.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 ''username' AS SELECT * FROM original_table' at line 1")
uname = blabla#bla.com
conn = pymysql.connect(
host="db.host",
port=int(3306),
user=user,
passwd=password,
db=db,
charset='utf8mb4'
)
cur = conn.cursor()
table_name = uname.replace('#', '_').replace('.', '_')
print('TABLE NAME:', table_name)
cur.execute(""" CREATE TABLE %s AS SELECT * FROM original_table """, (table_name))
Parameter quoting is for quoting values. Quoting table names does not work, because in MySQL the way to quote a table name is by using backticks (`), not quotation marks.
MariaDB [test]> CREATE TABLE 'username' AS SELECT * FROM my_table;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''username' AS SELECT * FROM my_table' at line 1
In this cause you need to use string formatting to create the SQL statement (you can use backticks to defend against SQL-injection*):
cur.execute(""" CREATE TABLE `%s` AS SELECT * FROM original_table """ % table_name)
* I'm not an expert on SQL-injection, so do some research if table_name originates outside your application.

python | When using the pymysql library to implement the SQL database, there was a syntax error in the SQL statement that could not be resolved

the complete code:
import pymysql
db=pymysql.Connect(host="localhost",user="root",port=3306,db="spider")
cursor=db.cursor()
data={
'id':'20120001',
'name':'BOb',
'age':21
}
table='students'
keys=','.join(data.keys())
values =','.join(['%s'] * len(data))
**sql = "INSERT INTO {table}({keys}) VALUES({values}) ON DUPLICATE KEY UPDATE".format(table=table,keys=keys,values=values)**
update= ','.join(['{key}=%s'.format(key=key) for key in data])
sql += update
try:
if cursor.execute(sql,tuple(data.values())*2):
print("Succesful")
db.commit()
except Exception as e:
print(e.args)
db.rollback()
db.close()
the erro statement:
1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATEid='20120001',name='BOb',age=21' at line 1")
I don't know about the way to solve it.if you can help me,thank you very much for that.
UPDATEid='20120001',name ...
UPDATE is a keyword. id is a column name. UPDATEid is what?

Can't insert PDF file into MySQL db with Python

I'm stuck. I've been trying to insert a pdf file in to MySQL db but I can't. I've tried with mysql.connector and MySQLdb classes. I get nearly the same errors. I've read many posts about this issue. I tried commas, variables also. Here are my code and error;
import mysql.connector
db = mysql.connector.connect(host="127.0.0.1", user='root', password='masatablo', db='yukleme')
c = db.cursor()
acilacak_dosya = open("bizim.PDF", "rb")
yuklenecek_dosya = acilacak_dosya.read()
c.execute ("INSERT INTO pdfler (cizim) VALUES(%s)" %(yuklenecek_dosya))
db.commit()
db.close()
ERROR with mysql.connector:
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 'b'%PDF-1.4\r%\xe2\xe3\xcf\xd3\r\n4 0 obj\r<</Linearized 1/L 83892/O 6/E 79669/N ' at line 1
ERROR with MySQLdb:
_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 'b'%PDF-1.4\\r%\\xe2\\xe3\\xcf\\xd3\\r\\n4 0 obj\\r<</Linearized 1/L 83892/O 6/E 79669/N ' at line 1")
You'll need to use parameters, not string interpolation.
String interpolation with SQL is vulnerable to SQL injection attacks anyway.
c.execute("INSERT INTO pdfler (cizim) VALUES (%s)", (yuklenecek_dosya,))

Error to view my data from database

I'm new in this python and mysql. I attempt to view the first row of data from my database. This is my code:
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="", # your passwords
db="58c_t2d_10") # name of the database
# you must create a Cursor object.
# It will let you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * 58c_10")
# print all the first cell of all the rows
for row in cur.fetchall() :
print row[0]
And I got this error:
OperationalError: (1044, "Access denied for user ''#'localhost'
to database '58c_t2d_10'")
I've tried to sign in as root:
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 '58c_10' at line 1")
cur.execute("SELECT * From 58c_10")
u have missed from

SQL query using %s in Python 3.3

I'm trying to retrieve data from a MySQL-database.
A = "James"
query = ("SELECT * FROM DB.tblusers WHERE UserName = %s ")
c = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='DB')
cur1 = c.cursor()
cur1.execute(query, A)
Gives the following error message:
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 '%' at line 1
But the SQL works in the mySQL Workbench.
Any ideas?
A should be a tuple, try with A = ("James",)
see documentation of MySQLCursor.execute(operation, params=None, multi=False)
EDIT: added a comma, thanks to "swordofpain" (I learned something)

Categories

Resources