SQL is not working on DUPLICATE KEY UPDATE - python

I am updating an existing MySQL table with pymysql but failed. The error is:
pymysql.err.ProgrammingError: (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 'ON DUPLICATE KEY
And my code is here:
with conn.cursor() as cursor:
sql = '''
INSERT INTO `Tag` (`title`,`weight`) VALUES (%s,%s)
ON DUPLICATE KEY
UPDATE
title = VALUES(title),
weight = VALUES(weight)
'''
L1 = ['ins', 'ig', 'twitter', 'tiktok', 'ig']
values = list(set([(item, L1.count(item)) for item in L1]))
cursor.executemany(sql, values)
conn.commit()

Related

Inserting a list into MySQL table, id wise

I am trying to insert a list into 1 single column in a row .How do I make the list go in a column in the same row with the same ID? I cannot get the syntax right.
social_media is a list like this
['https://twitter.com/eddylazzarin?ref=cypherhunter', 'https://www.linkedin.com/in/eddy-lazzarin-66059749?ref=cypherhunter', 'https://a16z.com/author/eddy-lazzarin/?ref=cypherhunter']
This is my code
sql = cursor.execute(f"SELECT inv_id FROM Investors WHERE name =\'{name}\'")
pid = cursor.fetchone()
pidf = str(pid)[1:2]
pidff = int(pidf)
try:
cursor.execute("INSERT INTO team_members(inv_id,mem_name,picture,experience) VALUES(%s, %s, %s, %s)", (pidff, port_name, headshot, work_ex,))
list_str = '|'.join(str(item) for item in so_links)
cursor.execute(f"UPDATE team_members WHERE mem_name=\'{port_name}\' SET social_media ('{list_str}')")
raise e
inv_id is the FOREIGN_KEY.
However I cannot get the right syntax
Error:
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 mem_name='Eddy Lazzarin' SET social_media
('https://twitter.com/eddylazzar' at line 1
You have missing = in SET & wrong position of it
cursor.execute("UPDATE team_members SET social_media = %s WHERE mem_name=%s",(list_str,port_name))
see the docs

I've been tried to insert a record to sql table using tkinter with entry widget, but i got an sql syntax error

This is my update:
def submit():
nama = Nama.get()
tgl_lahir = tgl_Lahir.get()
alamat = Alamat.get()
no_telp = No_telp.get()
insert = (nama,tgl_lahir,alamat,no_telp)
#connect to database
db = pymysql.connect(db="db_petugas", host="localhost", passwd="", user="root")
#prepare cursor
cur = db.cursor()
#insert into petugas table
sql = "INSERT INTO petugas VALUES ("",%s, %s, %s, %s);"
#execute sql code
cur.execute(sql, insert)
db.commit()
db.close()
#delete the entry
Nama.delete(0, END)
tgl_Lahir.delete(0, END)
Alamat.delete(0, END)
No_telp.delete(0, END)
This is error what i got:
pymysql.err.ProgrammingError: (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 ''Vanes', '1 June 2003', 'Grand Hill 23', '091293812030')' at line 1")
It is not safe to use concatenation with sql queries through python as it is vulnerable to sql injection. I recommend trying out to use placeholder(%s) and parametric substitution, like:
sql = "INSERT INTO petugas VALUES (NULL, %s, %s, %s);" #Using placeholders
# execute sql code
cur.execute(sql,insert) #substituting the tuple as a parameter
db.commit()
db.close()
Hope this cleared your error, do let me know if any doubts.
Cheers

PYTHON error in SQL syntax while writing json to MYSQL database

I want to receive json data from MQTT and store it in my database.
When am executing my code am receiving this error:
mysql.connector.errors.ProgrammingError: 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 '%s)' at line 1
There is my code :
import mysql.connector
import json
mydb = mysql.connector.connect(
host="localhost",
user="***",
passwd="***",
database="database"
)
mycursor = mydb.cursor()
def DATA_REPARTITION(Topic, jsonData):
if Topic == "test":
#print ("Start")
INSERT_DEBIT(jsonData)
def INSERT_DEBIT(jsonData):
#Read json from MQTT
print("Start read data to insert")
json_Dict = json.loads(jsonData)
debit = json_Dict['debit']
#Insert into DB Table
sql = ("INSERT INTO debit (data_debit) VALUES (%s)")
val=(debit)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mycursor.close()
mydb.close()
Thanks for your help, am working on this problem for the last 2 days.
You've written your parameterized query properly for MySQL:
sql = ("INSERT INTO debit (data_debit) VALUES (%s)")
The problem is that you're passing in the arguments wrong:
val=(debit)
mycursor.execute(sql,val)
The parentheses don't make debit into a tuple of 1 value. They don't do anything at all; val is just the same value as debit.
But execute wants a sequence of separate values, not 1 value.
To fix this, you need to add a comma. Commas are what create tuples in Python:
val = debit,
If you're wondering why this raises a SQL error, instead of a Python error about val not being iterable… Most likely, val is a string. And strings are iterable. They just iterate their characters. If val is, say, '$100', then you're passing the arguments '$', '1', '0', and '0', to fit a parameterized query with only one parameter.

How to get the IDENTITY value when using INSERT ... OUTPUT with pyodbc

I am trying to get the ID of a newly inserted row by using OUTPUT. However, I encountered the HY010 error. The following query/code is what I use:
string = """
SET NOCOUNT ON;
DECLARE #NEWID TABLE(ID INT);
INSERT INTO dbo.t1 (Username, Age)
OUTPUT inserted.id INTO #NEWID(ID)
VALUES(?, ?)
SELECT ID FROM #NEWID
"""
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
the last line id = cursor.fetchone()[0] led to a HY010 error (see below). Any advice would be greatly appreciated!
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')
I was able to reproduce your issue, and I was able to avoid it by retrieving the id value immediately after the INSERT and before the commit. That is, instead of
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
I did
cursor.execute(string, "John Doe", 35)
id = cursor.fetchone()[0] # although cursor.fetchval() would be preferred
cursor.commit()
For me only this worked with Azure SQL Serverless (using pyodbc==4.0.28):
cursor.execute(insert_statement, param_value_list)
cursor.execute("SELECT ##IDENTITY AS ID;")
return cursor.fetchone()[0]
If you're using SQLAlchemy with an engine, then you can retrieve the PyODBC cursor like this before running the query and fetching the table ID.
connection = sql_alchemy_engine.raw_connection()
cursor = connection.cursor()
result = cursor.execute(
"""
INSERT INTO MySchema.MyTable (Col1, Col2) OUTPUT INSERTED.MyTableId
VALUES (?, ?);
""",
col1_value,
col2_value,
)
myTableId = cursor.fetchone()[0]
cursor.commit()
print("my ID is:", myTableId)

python mysql insert error

I keep getting the error information after running this line of code
query = ("INSERT INTO Movies" "(movie_id,movie_name,movie_year,duration,score,storyline,genre,poster)"
"VALUES (%(ID)s,%(name)s,%(year)s,%(runtime)s,%(rating)s,%(storyline)s,%(genre)s,%(links)s)") #args = (ID,name,year,runtime,rating,storyline,genre,links)
cursor.execute(query)
con.commit()
The format is from mysql document
the error message 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 '%(ID)s,%(name)s,%(year)s,%(runtime)s,%(rating)s,%(storyline)s,%(genre)s,%(links)' at line 1
You are missing the query parameters:
cursor.execute(query, args)
where args, since you are using named parameters, has to be a dictionary where the keys should correspond to the parameter names:
args = {
"name": "some name",
"year": 1962,
# ...
}
As a side note, you can put your query into a multi-line string for readability:
query = """
INSERT INTO
Movies
(movie_id, movie_name, movie_year, duration, score, storyline, genre, poster)
VALUES
(%(ID)s, %(name)s, %(year)s, %(runtime)s, %(rating)s, %(storyline)s, %(genre)s, %(links)s)
"""

Categories

Resources