Python refuses to execute an sql query
I want to execute an insert sql query with python language in Pycharm.
An error is launched after executing the code below:
import mysql.connector
stock = mysql.connector.connect(
host="localhost",
user="root",
passwd="admin2020",
database="stock"
)
sql = "INSERT INTO produit(code, nom, prix_unitaire, tva, quantite) VALUES(%s,%s,%f,%f,%d)"
valeurs = ("LAM","lampe",0.9,0.19,10)
mycursor = stock.cursor()
mycursor.execute(sql, valeurs)
The error message is:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
You're confusing %s used as a parameter marker for a query, and %s (%d, %f, etc) used in Python string formatting. In your queries you should use just %s, the database driver will format the query for you:
sql = ("INSERT INTO produit(code, nom, prix_unitaire, tva, quantite) "
"VALUES (%s, %s, %s, %s, %s)")
valeurs = ("LAM", "lampe", 0.9, 0.19, 10)
mycursor.execute(sql, valeurs)
Try this one
sql = "INSERT INTO produit(code, nom, prix_unitaire, tva, quantite) VALUES(%s,%s,%f,%f,%d)"%("LAM","lampe",0.9,0.19,10)
mycursor = stock.cursor()
mycursor.execute(sql)
Related
I'm trying to insert a list into multiple columns in a mysql database.
But I keep getting this error: "Not all parameters were used in the SQL statement"
I'm new to this, but as I understand it, I'm supposed to use question marks in the statement to avoid SQL Injections.
This is the script:
import mysql.connector
wlcdb = mysql.connector.connect(
host="fqdn-server",
user="db-user",
password="sure",
database="cisco_wlc")
sqlcursor = wlcdb.cursor()
liste = ['3HETF3WP', 'DHP4QB6B', 'TQDAEPRY', 'Q7GFC2A6', 'DVXD3PXX']
params = ['?' for item in liste]
print (params)
sql = 'INSERT INTO wlc_mpsk (field0, field1, field2, field3, field4) VALUES (%s);' % ','.join(params)
print (sql)
sqlcursor.execute(sql, liste)
And when executing, the error comes:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Can anyone help me?
Thank you
The code below will work:
sqlcursor = wlcdb.cursor()
liste = ['3HETF3WP', 'DHP4QB6B', 'TQDAEPRY', 'Q7GFC2A6', 'DVXD3PXX']
sql = 'INSERT INTO wlc_mpsk (field0, field1, field2, field3, field4) VALUES (%s, %s, %s, %s, %s)'
sqlcursor.execute(sql, liste)
wlcdb.commit()
liste = ['3HETF3WP', 'DHP4QB6B', 'TQDAEPRY', 'Q7GFC2A6', 'DVXD3PXX']
sql = "INSERT INTO wlc_mpsk (field0, field1, field2, field3, field4) VALUES (%s);" % ("'"+"','".join(liste)+"'")
print(sql)
It's easier if you write this
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
I have problem with storing values of a python dictionary as data to an existing mysql table
I tried to use the code below but it's not working.
db = mysql.connect(
host="localhost",
user="root",
passwd="123456",
database="tgdb"
)
cursor = db.cursor()
val = ', '.join("'" + str(x) + "'" for x in dict.values())
sql = "INSERT INTO tgdb.channel(user_name, image_url, name,
number_of_members, description, channel_url) VALUES (%s, %s, %s, %s, %s,
%s)"
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record inserted.")
"you have an error in your SQL syntax"
As writed #Torxed shouldn't translate dict in string, you can write just that:
cursor.execute(sql, list(dict.values())
hi I am doing the python mysql at this project, I initial the database and try to create the table record, but it seems cannot load data to the table, can anyone here can help me out with this
import mysql.connector
mydb = mysql.connector.connect( host="localhost",user="root",password="asd619248636",database="mydatabase")
mycursor = mydb.cursor()
mycursor.excute=("CREATE TABLE record (temperature FLOAT(20) , humidity FLOAT(20))")
sql = "INSERT INTO record (temperature,humidity) VALUES (%d, %d)"
val = (2.3,4.5)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
and the error shows "Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Changing the following should fix your problem:
sql = "INSERT INTO record (temperature,humidity) VALUES (%s, %s)"
val = ("2.3","4.5") # You can also use (2.3, 4.5)
mycursor.execute(sql,val)
The database API takes strings as arguments, and later converts them to the appropriate datatype. Your code is throwing an error because it isn't expecting %d or %f (int or float) datatypes.
For more info on this you can look here
simply change insert method to
sql = "INSERT INTO record (temperature,humidity) VALUES (%s, %s)"
then it works fine
This works for me.
# Insert from dataframe to table in SQL Server
import time
import pandas as pd
import pyodbc
# create timer
start_time = time.time()
from sqlalchemy import create_engine
df = pd.read_csv("C:\\your_path_here\\CSV1.csv")
conn_str = (
r'DRIVER={SQL Server Native Client 11.0};'
r'SERVER=Excel-Your_Server_Name;'
r'DATABASE=NORTHWND;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
cursor = cnxn.cursor()
for index,row in df.iterrows():
cursor.execute('INSERT INTO dbo.Table_1([Name],[Address],[Age],[Work]) values (?,?,?,?)',
row['Name'],
row['Address'],
row['Age'],
row['Work'])
cnxn.commit()
cursor.close()
cnxn.close()
I am facing error while trying to iteratively insert values in MySQL table. I am not sure if the insert statement is correct? or do we have any better way of inserting values in my table.
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax;
import mysql.connector
from collections import defaultdict
cnx = mysql.connector.connect(user='root', password='hadoop',
host='localhost',
database='test')
lines = defaultdict(dict)
with open("test.txt") as f:
for line in f:
parts = line.split()
key = tuple(parts[1:3]) # unique key with servername and datetime
lines[key][parts[0]] = parts[3]
lines[key]["servername"] = parts[2]
lines[key]["datetime"] = parts[1]
res = list(lines.values())
try:
cursor = cnx.cursor()
for index in range(len(res)):
cursor.execute("""
insert into cpu_util_all (servername,date_time,cpu_number,cpu_user,cpu_nice,cpu_system,cpu_wait,cpu_idle) values ('%s', '%s', '%s', '%s','%s', '%s', '%s', '%s') % (res[index]["servername"],res[index]["datetime"],res[index]["cpunumber"],res[index]["cpuuser"],res[index]["cpunice"],res[index]["cpusystem"],res[index]["cpuwait"],res[index]["cpudile"])
""")
cnx.commit()
cursor.close()
finally:
cnx.close()
print("Inserted successfully")
The problem is that you're trying to do string substitution in the query itself. Further, you should allow MySQLdb to parse the parameter values for you, e.g.:
cursor.execute("""
insert into cpu_util_all
(servername,date_time,cpu_number,cpu_user,
cpu_nice,cpu_system,cpu_wait,cpu_idle)
values (%s, %s, %s, %s, %s, %s, %s, %s)""",
(res[index]["servername"],res[index]["datetime"],
res[index]["cpunumber"],res[index]["cpuuser"],
res[index]["cpunice"],res[index]["cpusystem"],
res[index]["cpuwait"],res[index]["cpudile"]
)
)