ProgrammingError: Not all parameters were used in the SQL statement - python

Need a little help here, think I have tried everything to fix this issue but keep getting the same error message ProgrammingError: Not all parameters were used in the SQL statement
CODE:
mydb = mysql.connector.connect(host="localhost", user="xx", passwd="", database="xx")
mycursor = mydb.cursor()
sql = "INSERT INTO authors(id, first_name, last_name, photo) VALUES(%s, %s, %s,%s)"
values = ['''(1,'Herbert','Methley','NULL'),
(2,'Olive','Wellwood','NULL'),
(3,'Francis','Tugwell ','NULL'),(4,'Randolph','Henry Ash','NULL'),
(5,'Christabel','LaMotte ','NULL'),(7,'Robert','Dale Owen','NULL'),
(12,'Leonora','Stern ','NULL'),(14,'Mrs.','Lees ','NULL'),(19'Josephine','M. Bettany','NULL'),
(20,'Kester','Bellever ','NULL'),(22,'Sylvia','Leigh ','NULL'),(24,'Elizabeth','Temple ','NULL'),
(25,'Marsha','Patterson ','NULL'),(26,'Samuel','Humber ','NULL'),(27,'James','Fallon ','NULL'),
(28,'Beatrice','Quinn ','NULL'),(29,'Susan','Magar ','NULL'),(30,'Clinton','York ','NULL'),
(31,'Canton','Lee ','NULL'),(32,'Rod','Keen ','NULL'),(33,'Hilda','Simpson ','NULL'),
(34,'S.','M. Justice','NULL'),(35,'Charles','Green ','NULL'),(36,'Richard','Brautigan ','NULL'),
(37,'Bill','Lewis ','NULL'),(38,'Chuck',' ','NULL'),(39,'Doctor','O. ','NULL'),
(40,'Harlow','Blade ','NULL'),(41,'Barbara','Jones ','NULL'),(42,'Fred','Sinkus ','NULL'),
(43,'Thomas','Funnel ','NULL'),(44,'Patricia','Evens Summers','NULL'),
(45,'Reverend','Lincoln Lincoln','NULL'),(47,'Edward','Fox ','NULL')''']
mycursor.executemany(sql, values)
mydb.commit()
print(mycursor.rowcount, "was inserted")
ERROR MESSAGE:
Traceback (most recent call last):
File "C:\Users\xxx\Documents\Python Scripts\PYTHONMYSQL_TEST.py",
line 30, in
mycursor.executemany(sql, values)
File
"C:\Users\xxx\AppData\Local\Programs\Anaconda\lib\site-packages\mysql\connector\cursor.py",
line 668, in executemany
stmt = self._batch_insert(operation, seq_params)
File
"C:\Users\xxx\AppData\Local\Programs\Anaconda\lib\site-packages\mysql\connector\cursor.py",
line 614, in _batch_insert
"Not all parameters were used in the SQL statement")
ProgrammingError: Not all parameters were used in the SQL statement
Any help would be appreciated, I believe I have given everyone all the information needed. If I have forgot something please let me know
thanks

Related

Inserting csv into MySQL database with python library mysql.connector

I have trouble with insert of csv data into MySQL tabel with mysql.connector .
The code I use looks like this :
import mysql.connector
import csv
andreport = 'testowa.csv'
cnx = mysql.connector.connect(
user='xxxxx',
password='xxxxx',
host='xxxxxx',
database='xxxxx')
cursor = cnx.cursor()
with open(andreport, 'r') as csv_data:
for row in csv_data:
cursor.execute(
"INSERT INTO flex(date, Store, Vendor, Shelf)"
"VALUES({},{},{},{})", row)
cnx.commit()
cursor.close()
cnx.close()
print("Done")
The error I get :
C:\Users\Iw4n\PycharmProjects\Learning\venv\Scripts\python.exe C:/Users/Iw4n/PycharmProjects/Learning/Orange_android_MySQL_insertion.py
Traceback (most recent call last):
File "C:/Users/Iw4n/PycharmProjects/Learning/Orange_android_MySQL_insertion.py", line 15, in <module>
cursor.execute(
File "C:\Users\Iw4n\PycharmProjects\Learning\venv\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\Iw4n\PycharmProjects\Learning\venv\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\Iw4n\PycharmProjects\Learning\venv\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
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 '},{},{},{})' at line 1
When i wrapped {} into '' , as many rows as were in csv been inserted into datbase as {},{}
same story goes for %s if I use it , i got the same error as above, when it's wrapped in '' , %s is insetred into database.
I also found information to add f in fron of "INSERT~ but it did not help.
Can anyone give me some suggestion on how to overcome this and correctly insert data to MySQL ?
Final code that is working as intended :
import mysql.connector
import csv
andreport = 'testowa.csv'
cnx = mysql.connector.connect(
user='xxxxx',
password='xxxxx',
host='xxxxx',
database='xxxxx')
cursor = cnx.cursor()
with open(andreport, mode='r') as csv_data:
reader = csv.reader(csv_data, delimiter=';')
csv_data_list = list(reader)
for row in csv_data_list:
cursor.execute("""
INSERT INTO flex(
date, Agency, MediaSource, Campaign)
VALUES(%s,%s,%s,%s)""",
(row[0], row[1], row[2], row[3]))
cnx.commit()
cursor.close()
cnx.close()
print("Done")
I'm guessing that seems the problem is that you passed one argument (row) instead of four. So try this:
cursor.execute("""
INSERT INTO flex(date, Store, Vendor, Shelf)
VALUES(%s,%s,%s,%s)""",(row[0], row[1], row[2], row[3], ))
Looking at the documentation for MySQLCursor.excute() method, it seems like adding some %s as the parameters in your insert statement might fix this?
import mysql.connector
import csv
andreport = 'testowa.csv'
cnx = mysql.connector.connect(
user='xxxxx',
password='xxxxx',
host='xxxxxx',
database='xxxxx')
cursor = cnx.cursor()
insert_statement = (
"INSERT INTO flex(date, Store, Vendor, Shelf)"
"VALUES (%s, %s, %s, %s)"
)
with open(andreport, mode='r') as csv_data:
reader = csv.reader(csv_data, delimiter=';')
csv_data_list = list(reader)
for row in csv_data_list:
cursor.execute(insert_statement, row)
cnx.commit()
cursor.close()
cnx.close()
print("Done")
Let me know if this gets you anywhere, or if you see a new error!
Edit: updated CSV reading to convert to a list.

Why does execute () append null values and executemany() doesn't?

While using MySQL through python, on using execute() function null values are getting updated in the specific table, but on using executemany() the null values are returning errors.
The working commands:
mycursor = mydb.cursor()
mycursor.execute("INSERT INTO users (name, fav) VALUES('John', null)"
mydb.commit()
The code that doesn't work:
mycursor = mydb.cursor()
sql = "INSERT INTO users (name, fav) VALUES(%s, %s)"
val =[
('Samantha', 154),
('Thalia', 155),
('Jacobs', null),
('Jamie', null)
]
mycursor.executemany(sql, val)
mydb.commit()
The error generated is as follows:
Traceback (most recent call last):
File "demo_python.py", line 14, in
('Jacobs', null),
NameError: name 'null' is not defined

python3 mysql connector module throws exception - ValueError: Could not process parameters

I am trying to get past this error that is haunting me. I built a simple script to populate a single column database.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE IF NOT EXISTS data(pass_word VARCHAR(20))")
val = 'test'
sql = "INSERT INTO data(pass_word) VALUES '%s'"
mycursor.execute(sql, (val))
mydb.commit()
It creates the table no problem, so I know the connector is working. But it refuses to insert the val into pass_word.
It throws the following exception
Press ENTER or type command to continue
Traceback (most recent call last):
File "sql-try.py", line 19, in <module>
mycursor.execute(sql, (val))
File "/usr/local/lib/python3.6/dist-packages/mysql/connector/cursor_cext.py", line 248, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "/usr/local/lib/python3.6/dist-packages/mysql/connector/connection_cext.py", line 538, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
I think the issue was that my table only had one column, so when I was passing the val, val itself needed to be a tuple. Changing it to (sql, (val,)) did not address the issue. When I created a table with more than one column, the problem went away.
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="mydatabase"
)
mycursor = mydb.cursor()
myname = 'jimmy'
password = 'grizwald'
mycursor.execute("CREATE TABLE IF NOT EXISTS data3(my_name VARCHAR(20), pass_word VARCHAR(20))")
val = (myname, password )
sql = "INSERT INTO data3(my_name, pass_word) VALUES (%s, %s)"
mycursor.execute(sql, val)
mydb.commit()

In Python, how to define a function which inserts the arguments of the function to a table in database?

i want to define a function (named "kayitEkle") which inserts the arguments of function to a table (named "biTablo") in database:
import sqlite3
connect = sqlite3.connect("obs.db")
cursor = connect.cursor()
def tabloOlustur():
cursor.execute("CREATE TABLE IF NOT EXISTS biTablo(ad TEXT, soyad TEXT, numara TEXT, puan REAL)")
connect.commit()
tabloOlustur()
def kayitEkle(ad, soyad, numara, puan):
cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(? ? ? ?)",(ad,soyad,numara,puan))
connect.commit()
kayitEkle('ahmet', 'yılmaz', '08067', 50)
but i get this message:
Traceback (most recent call last):
File "C:/Users/pc/PycharmProjects/ikinciBahar/ogrenmeDatabase.py", line 234, in <module>
kayitEkle('ahmet', 'yılmaz', '08067', 50)
File "C:/Users/pc/PycharmProjects/ikinciBahar/ogrenmeDatabase.py", line 231, in kayitEkle
cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(? ? ? ?)",(ad,soyad,numara,puan))
sqlite3.OperationalError: near "?": syntax error
what is wrong? what should i do?
You should probably use python .format and change your line from
cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(? ? ? ?)",(ad,soyad,numara,puan))
to
cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES({},{},{},{})".format(ad,soyad,numara,puan))
In your cursor.execute use VALUES(%s, %s, %s, %s)
You need to compose the string correctly. Asumming ad,soyad,numara are strings and puan is a number:
cursor.execute(INSERT INTO biTablo VALUES(\"%s\", \"%s\", \"%s\", %f);" % (ad,soyad,numara,puan))
If I am not wrong this should work:
cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(%s, %s, %s, %s)", (ad,soyad,numara,puan))

MySQLdb: Operand should contain 1 column(s)

I am trying to insert some data into a MySQL database, using Python and MySQLdb. When I execute the following function in my program, MySQL returns error "1241, 'Operand should contain 1 column(s)'"
User, password and database are correct, the table is existing and all rights are granted.
def write_to_mysql(pname, dat, like, reachs, talker, friendsfans):
''
try:
con = mdb.connect(user='user', passwd='password', host='localhost', db='database');
except Exception. err:
print(err)
with con:
cur = con.cursor()
cur.execute("INSERT INTO fbinsights (page, datum, likes, reach, talking, fanfriends) VALUES( %s, %s, %s, %s, %s, %s)", (pname, dat, like, reachs, talker, friendsfans))
connection.commit()
Where's the mistake?
Full traceback:
File "insights.py", line 111, in <module>
main()
File "insights.py", line 108, in main
write_to_mysql(PAGE_NAME, date, likes_atm, reach_day, talking_day, friends_of_fans)
File "insights.py", line 90, in write_to_mysql
cur.execute("INSERT INTO fbinsights (page, datum, likes, reach, talking, fanfriends) VALUES( %s, %s, %s, %s, %s, %s)", (pname, dat, like, reachs, talker, friendsfans))
File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-freebsd-9.0-RELEASE-p3-amd64.egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-freebsd-9.0-RELEASE-p3-amd64.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')
#schlamar answered it. Wrong types passed to MySQL.
I had this error when I was generating a SELECT query with columns to select enclosed (by mistake) in parentheses: SELECT (id, name, age) FROM members;
Note that it does not raise this error if you have just one column listed in parentheses.

Categories