Unable to iteratively insert values in Python-MySQL tables - python

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"]
)
)

Related

Mysql table name getting unwanted quotes resulting table does not exist error

import mysql.connector
def add_features_to_db(stockname, timeframe, date, feature):
try:
conn = mysql.connector.connect(
user='root', password='', host='localhost', database='fx003')
cursor = conn.cursor()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO `%s` (date, trend) VALUES ( `%s`, `%s` )"""
record = (dbtable, date, feature)
cursor.execute(mySql_insert_query, record)
conn.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
add_features_to_db("aud-cad", "_30mins", "2021-09-24 21:00:00", "Short")
I have the code above and giving me the below error:
Failed to insert into MySQL table 1146 (42S02): Table 'fx003.'aud-cad_30mins'' doesn't exist
aud-cad_30mins table does exist and an insert query like below doing its job:
mySql_insert_query = """INSERT INTO aud-cad_30mins (date, trend) VALUES ( "2021-09-24 21:00:00","Short" )"""
So when I try to use variables in the query, it gives the error. Why the table name getting unwanted quotes? Checked several tutorials but couldn't find a solution, any ideas?
The table name should be hardcoded in the query string instead of having it there as a placeholder %s, which is meant for the values to be inserted. So if you have the table name in the variable, you can replace it via format() before calling cursor.execute()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO {} (date, trend) VALUES ( %s, %s )""".format(dbtable)
see the examples in the docs
edit: as Bill mentioned in the comment, dont add the backticks around the %s placeholders.

Insert list into mysql using python - Not all parameters were used in the SQL statement

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

How to solve that execute() takes no keyword arguments

I want to insert data to database table with these python 3 script,
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, params=val)
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
but I got error type "TypeError: execute() takes no keyword arguments". could someone help solve this error?
You can directly pass the query and values with it in the form of list.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, list(val))
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
Or you can use executemany to insert all the values at one time.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
cursor.executemany(sql, values)
db.commit()
print("{} data ditambahkan".for

Fix %s sql query in python

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)

importing values of a python dictionary as data to an existing mysql table

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())

Categories

Resources