When executing the following code in order to insert multiple values through a variable from python into mysql, I get:
'Incorrect number of arguments executing prepared statement ' error after executing 'result = cursor.executemany(sql_insert_query, records_to_insert)'
if i remove 'prepared=True', the error becomes:
'Not all parameters were used in the SQL statement'
import mysql.connector
connection = mysql.connector.connect(host='localhost',
database='majorprediction',
user='root',
password='')
records_to_insert = [ ('x') ,
('y'),
('z') ]
sql_insert_query = """ INSERT INTO majorpred (Major)
VALUES (%s) """
cursor = connection.cursor(prepared=True)
result = cursor.executemany(sql_insert_query, records_to_insert)
connection.commit()
Can anyone specify where is the problem?
You are passing a list of characters instead of tuples. For instance, if you try and run:
for record in records_to_insert:
print(record, isinstance(record, str), isinstance(record, tuple))
You will get:
x True False
y True False
z True False
To create tuples with a single element in python you can do the following:
records_to_insert = [
('x',),
('y',),
('z',)
]
If you have a list of parameters and want to cast all of them to tuple you can do as follows:
list_of_elements = list("list_of_characters")
tuples = [
tuple(e) for e in list_of_elements
]
Hope this helps!
Related
I'm trying to make a form in which my user can update their login username (info is in a MySQL database) but I get this error when I run the code and enter test values:
Error Dui to : 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 '%s WHERE client_ID = '0001'' at line 1
I desperately need help. This the code
old_uname = StringVar()
new_name = StringVar()
def update_uname():
if old_uname.get()==" " or new_name.get()==" ":
messagebox.showerror("Error" , "All Fields Are Required" , parent = wintask)
else:
try:
con = mysql.connector.connect(host="<>", user="<>", password="<>",database="<>")
cur = con.cursor()
update_command = "UPDATE login_information SET username = %s WHERE client_ID = '0001'"
val = (new_name.get())
cur.execute(update_command, val)
con.commit()
messagebox.showinfo("Success", "Username has been updated!", parent=wintask)
except Exception as es:
messagebox.showerror("Error" , f"Error Dui to : {str(es)}", parent = wintask)
PS: I have no trouble w the SQL connection. I'm fairly new to coding
I referred to the documentation https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
and I think the following is relevant to you:
The parameters found in the tuple or dictionary params are bound to the variables in the operation.
and then the Note:
In Python, a tuple containing a single value must include a comma. For example, ('abc') is evaluated as a scalar while ('abc',) is evaluated as a tuple.
Your code:
new_name = StringVar()
....
val = (new_name.get())
cur.execute(update_command, val)
So the parameter params is a string:
>>> a="test"
>>> (a)
'test'
>>> b=(a)
>>> type(b)
<class 'str'>
>>> c=(a,)
>>> type(c)
<class 'tuple'>
let you try cur.execute(update_command, (val,)) # the comma after val
I try:
cursor = client.cursor()
query = "INSERT INTO t_table (column_1,column_2) VALUES (%s)"
values = ['temp', 'temp']
cursor.execute(query, values)
client.commit()
print(cursor.rowcount, "record inserted")
finally:
client.close()
The error
"MySQLdb._exceptions.ProgrammingError: not all arguments converted
during bytes formatting"
keeps appearing. I have gone through the syntax error and GEOMETRY field error but I'm stuck at this one.
For two values you need also to placeholders
try:
cursor = client.cursor()
query = "INSERT INTO t_table (column_1,column_2) VALUES (%s,%s)"
values = ['temp', 'temp']
cursor.execute(query, values)
client.commit()
print(cursor.rowcount, "record inserted")
finally:
client.close()
Running Python 3.7.2 32 bit on Windows 7 and using pyodbc package 4.0.25-cp27 32bit
I have tried multiple ways of passing through the params and keep getting the above error:
TypeError: ('Params must be in a list, tuple, or Row', 'HY000')
my inputfile is a txt file containing this:
TEST ,EU ,Totals , 30, 0.61, 0.00000000,GOLD ,01/03/2019,
TEST ,EU ,SubTotals , 40, 0.63, 0.00000000,GOLD ,01/03/2019,
A few versions:
qry = """INSERT INTO newtable ([Col1], [Col2], [Col3], [Col4], [Col5], [Col6], [Col7], [Col8]) VALUES (?,?,?,?,?,?,?,?);"""
with open (inputfile, "r") as afile:
for line in afile:
params = tuple(line.split(','))
cursor.executemany(qry, params)
conn.commit()
for the params value also tried:
params = list(line.split(','))
Also tried inserting all values into the list one by one:
params = list(line.split(","))
a = params[0]
b = params[1]
c = params[2]
d = params[3]
e = params[4]
f = params[5]
g = params[6]
h = params[7]
dbparams = [a,b,c,d,e,f,g,h]
cursor.executemany(qry,dbparams)
cursor.execute(qry, params[0:8]) worked
The executemany was causing the error - params must be in list, tuple or row
and without the [0:8] the list was passing through a '\n' at the end of the list causing the error - the SQL contains 8 parameter markers, but 9 parameters were supplied
Winning answer was:
cursor.execute(qry, params[0:8]) worked
thanks to #gordthompson for his prompt
I am trying to use the following function in R:
heritblup <- function(name) {
library(RMySQL)
library(DBI)
con <- dbConnect(RMySQL::MySQL(),
dbname ="mydab",
host = "localhost",
port = 3306,
user = "root",
password = "")
value1 <- 23;
rss<- paste0 ("INSERT INTO namestable
(myvalue, person)
VALUES ('$value1', '",name,"')")
rs <<- dbGetQuery (con, rss)
}
heritblup("Tommy")
But I keep getting this error:
Error in as.character.default()
: no method for coercing this S4 class to a vector Called from:
as.character.default()
I tried to change the paste function to this:
rss<- paste0 ("INSERT INTO namestable
(myvalue, person)
VALUES ($value1, ",name,")")
the error persists;
I have no idea whats wrong.
Please help
Couple of issues in code. I'm not sure if OP is attempting to insert records in database or fetch from database.
Assuming, based on query that he is expecting to insert data in database table.
The rule is that query should be prepared in R the way it will be executed in MySQL. Value replacement (if any) should be performed in R as MySQL engine will not have any idea about variables from R.
Hence, the query preparation steps should be done as:
rss <- sprintf("INSERT INTO namestable (myvalue, person) VALUES (%d, '%s')", value1, name)
# "INSERT INTO namestable (myvalue, person) VALUES (23, 'test')"
If data insert is goal then dbGetQuery is not right option per R documentation instead dbSendStatement() should be used for data manipulation. The reference from help suggest:
However, callers are strongly encouraged to use dbSendStatement() for
data manipulation statements.
Based on that query execution line should be:
rs <- dbSendStatement(con, rss)
ret_val <- dbGetRowsAffected(rs)
dbClearResult(rs)
dbDisconnect(con)
return(ret_val)
This is the code I am executing to extract data but the unicode's "u"
is not getting removed
cur=con.cursor()
e1=self.entry1.get()
e2=self.entry2.get()
e3=self.entry3.get()
e4=self.entry4.get()
cur.execute("insert into student13 values(?,?,?,?)",(e1,e2,e3,e4))
con.commit()
cur.execute("select * from student13")
ar=cur.fetchall()
>#fetching data from database
tkMessageBox.showinfo("records",ar)
You could try the ".encode" function
ar = u'unicode string'
ar = ar.encode('ascii')