How do i solve the following sql syntax error - python

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, :passw, :addrss, :DOB, :emil, :ag)' at line 1
THE CODE:
def submit():
my_cursor = mydb.cursor()
#INSERT INTO TABLE
my_cursor.execute("INSERT INTO madhav VALUES (:Username, :passw, :addrss, :DOB, :emil, :ag)",
{
'Username': Username.get(),
'passw' : passw.get(),
'addrss' : addrss.get(),
'DOB' : DOB.get(),
'emil' : emil.get(),
'ag' : ag.get()
})
mydb.commit()
mydb.close()
# Clear The Text Boxes
Username.delete(0,END)
passw.delete(0,END)
addrss.delete(0,END)
DOB.delete(0,END)
emil.delete(0,END)
ag.delete(0,END)
The above function is used to insert values into a database using a GUI

That's not how you use named parameters in mydb. The correct syntax for such a parameter is %(name)s. So, in your case:
my_cursor.execute("INSERT INTO madhav VALUES (%(Username)s, %(passw)s, %(addrss)s, %(DOB)s, %(emil)s, %(ag)s)",
{
'Username': Username.get(),
'passw' : passw.get(),
'addrss' : addrss.get(),
'DOB' : DOB.get(),
'emil' : emil.get(),
'ag' : ag.get()
})

The values take type of variable, like string, integar etc.
So you code will become
stmt= (
"INSERT INTO madhav (Username, passw, addrss, DOB, emil, ag) "
"VALUES (%s, %s, %s, %s, %s, %s)"
)
Because all fielda are string type so there is %s otherwise for integar it will be %i
Next you can bound this stmt with data to execute.
data = (Username.get(), passw.get(), addrss.get(), DOB.get(),emil.get(),ag.get())
my_cursor.execute(stmt, data)
See these docs for more info
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

Related

Psycopg2, how to alias input values in sql query?

I need to update many rows with pyscopg based on input I receive. Input is list of tuples containing 3 elements.
input = [("Programing Langugae", "Python", "some path to img")]
_query_update = f"""UPDATE {TABLE} as t SET (category, name, img_path) = VALUES (%s, %s, %s) as t2 WHERE t.name = t2.name"""
db.cursor.executemany(_query_update, records)
db.connection.commit()
It throws me
psycopg2.errors.SyntaxError: syntax error at or near "("
LINE 1: ...ills as t SET (category, name, img_path) = VALUES ('framewor...
I need to use my middle value from the input in WHERE statement so I need to alias it somehow, because raw %s, %s, %s gives me nothing. How can I do it?

Problem to insert with psycopg2 with python

I'm trying to insert some rows, but this problema occurs:
TypeError: not all arguments converted during string formatting
sql code:
f"""insert into {table} ({insert}) VALUES ({formating}) ON CONFLICT ({', '.join(key)}) DO UPDATE SET ({insert}) = ({excluded})"""
sql translate:
insert into public.atend (cd_atendimento, cd_ori_ate, cd_paciente, op_type) VALUES (%s, %s, %s, %s) ON CONFLICT (cd_atendimento) DO UPDATE SET (cd_atendimento, cd_ori_ate, cd_paciente, op_type) = (EXCLUDED.cd_atendimento, EXCLUDED.cd_ori_ate, EXCLUDED.cd_paciente, EXCLUDED.op_type)

Executing multiple SQL queries with Python Flask

I have a python function which should execute 2 SQL queries. I have found that it is impossible to execute 2 queries in one command at once, so as a workaround I created a list of my queries and try to iterate over it with execute command. However nothing is added to MySQL table. Here is the code:
#app.route('/addComment', methods=['POST'])
def addComment():
try:
if session.get('user'):
_description = request.form['description']
_user = session.get('user')
_term_id = request.form['termID']
_time = datetime.now()
operation = ['"INSERT INTO comments (description, user, termID, time) VALUES (%s, %s, %s, %s)", (_description, _user, _term_id, _time)', '"INSERT INTO history (user, term, time) VALUES (%s, %s, %s)", (_user, _term_id, _time)']
conn = mysql.connect()
cursor = conn.cursor()
for item in operation:
cursor.execute()
conn.commit()
data = cursor.fetchall()
if len(data) == 0:
conn.commit()
return json.dumps({'status':'OK'})
else:
return json.dumps({'status':'ERROR'})
except Exception as e:
return json.dumps({'status':'Unauthorized access'})
finally:
cursor.close()
conn.close()
Could you please help me?
Errors in your code lies in the following areas:
A. On iteration sql statement is not passed to execute()
Should be:
for item in operation:
cursor.execute(item)
conn.commit()
B. Invalid parameterization
'"INSERT INTO comments (description, user, termID, time) VALUES (%s, %s, %s, %s)", (_description, _user, _term_id, _time)'
This string statement doesn't apply variables to SQL statement string. Depending on your value types you should decide whether to add ' (apostrophe) or not. More safely would be to pass parameters to .execute() function. Example below.
cursor.execute(
"INSERT INTO comments (description, user, termID, time) VALUES (:description, :user, :term_id, :time)",
description=_description,
user=_user,
term_id=_term_id,
time=_time
)

(1064, "You have an error in your SQL syntax; .. for the right syntax to use near '%s, %s, %s, %s, %s)' at line 1") [duplicate]

This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 4 years ago.
I'm trying to insert data into my mysql database, but I always get the error that something is wrong with the parameters, that I'd like to add into my insert statement, I tried all kinds of solutions and the one with the 's', 's' worked, it got inserted into my db.
Has anybody got an idea what can be wrong?
Thanks.
try:
conn = mysql.connect()
cursor = conn.cursor()
insert_cmd = "INSERT INTO TBTAB VALUES(%s, %s, %s, %s, %s)"
#insert_cmd = "INSERT INTO TBTAB VALUES('s', 's', 's', 's', 's')"
# insert_cmd = "INSERT INTO TBTAB VALUES(?, ?, ?, ?, ?)"
tpa= ("szilva", "barack", "meggye", "alma", "korte")
#cursor.execute("INSERT INTO TBTAB (UserName, Email, TextBoxCont, NodeChosen, CurDate) VALUES ('Caal', 'TomErichsen', 'Svanger', '400esd6', 'Nqdwasorway');")
cursor.execute(insert_cmd.format(tpa))
conn.commit()
return render_template('form.html')
except Exception as e:
return str(e)
error:
(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 '%s, %s, %s, %s, %s)' at line 1")
You should pass the query parameters as a tuple to cursor.execute() instead of interpolating them into the query, i.e.:
cursor.execute(insert_cmd, tpa)
%s in the query serves as a placeholder for a single parameter.

Inserting Variables MySQL Using Python, Not Working

I want to insert the variable bob, and dummyVar into my table, logger. Now from what I can tell all I should need to do is, well what I have below, however this doesn't insert anything into my table at all. If I hard-code what should be written (using 'example' then it writes example to the table, so my connection and syntax for inserting is correct to this point). Any help would be more than appreciated!
conn = mysql.connector.connect(user='username', password='password!',
host='Host', database='database')
cursor = conn.cursor()
bob = "THIS IS AN EXAMPLE"
dummyVar = "Variable Test"
loggit = ("""
INSERT INTO logger (logged_info, dummy)
VALUES
(%s, %s)
""", (bob, dummyVar))
cursor.execute(loggit)
conn.commit()
I have also tried this:
loggit = ("""
INSERT INTO logger (logged_info, dummy)
VALUES
(%(bob)s,(Hello))
""", (bob))
and:
bob = "THIS IS AN EXAMPLE"
dummyVar = "Variable Test"
loggit = ("""
INSERT INTO logger (logged_info, dummy)
VALUES
(%s, %s)
""", (bob, dummyVar))
cursor.execute(loggit, (bob, dummyVar))
conn.commit()
cursor.execute(loggit, (bob, dummyVar))
conn.commit()
You need to pass the SQL statement and the parameters as separate arguments:
cursor.execute(loggit[0], loggit[1])
or use the variable argument syntax (a splat, *):
cursor.execute(*loggit)
Your version tries to pass in a tuple containing the SQL statement and bind parameters as the only argument, where the .execute() function expects to find just the SQL statement string.
It's more usual to keep the two separate and perhaps store just the SQL statement in a variable:
loggit = """
INSERT INTO logger (logged_info, dummy)
VALUES
(%s, %s)
"""
cursor.execute(loggit, (bob, dummyVar))

Categories