incorrect binding supplied in sqlite3 - python-3.x

I am trying to create a database from a cif file, and getting an odd error:
import sqlite3 as sq
sqlfile = "mats.db"
tabnm = "elems"
id_col = "Properties"
val_col = "Value"
conn = sq.connect(sqlfile)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS Trial
(Properties text, Name text, Phase text, AbM text, AbB text, Cpre text)''')
lists = []
filename = "/var/tmp/1101142.cif"
fullparams=["_journal_coden_ASTM" , "_journal_issue", "_journal_name_full"
,"_journal_page_first","_journal_page_last","_journal_paper_doi"
,"_journal_volume","_journal_year","_chemical_formula_sum"
,"_chemical_formula_weight","_space_group_IT_number","_symmetry_cell_setting"
,"_symmetry_space_group_name_Hall","_symmetry_space_group_name_H-M ","_atom_sites_solution_primary"
,"_atom_sites_solution_secondary ","_audit_creation_method","_cell_angle_alpha"
,"_cell_angle_beta","_cell_angle_gamma","_cell_formula_units_Z"
,"_cell_length_a","_cell_length_b","_cell_length_c"
,"_cell_measurement_reflns_used","_cell_measurement_temperature","_cell_measurement_theta_max"
,"_cell_measurement_theta_min","_cell_volume"]
with open(filename, "r") as cif:
for line in cif:
for j in range(6):
if line.startswith(fullparams[j]):
# print(line)
lists.append(line.split()[-1])
print(lists)
c.executemany("INSERT INTO Trial VALUES(?, ?, ?, ?, ?, ?)",lists)
conn.commit()
While I have made sure the number is equal, I am still getting error:
python3 parse_cif.py
['CMATEX', '7', "Materials'", '1745', '1752', '10.1021/cm0513738']
Traceback (most recent call last):
File "parse_cif.py", line 36, in <module>
c.executemany("INSERT INTO Trial VALUES(?, ?, ?, ?, ?, ?)",lists)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 6, and there are 1 supplied.
I have no idea how it is counting supplied value 1. I have seen similar question already asked as:Python 3 SQLite3 - Incorrect number of bindings, sqlite3 - Incorrect number of bindings supplied but cant solve my problem.
Kindly help.

executemany() executes the same statement multiple. So it does not expect a list of paramters, but a list containing multiple parameter lists, one for each execution.
In this case 'CMATEX' looks like a list containing six characters, so it executes just fine. But the next list, '7', contains only a single value; this is the error you get.
To insert a single row, use execute() instead.

Related

Incorrect number of bindings supplied. The current statement uses 11, and there are 10 supplied

I´m Learning Coding and the Error Message from the Debugging confuse me a bit,
when i try to create a SQLlite Database with 11 statements, i have two different Errors.
here my Code:
import sqlite3
connection = sqlite3.connect("wtime1.db")
cursor = connection.cursor()
date = ("31.10.2022")
p_unit = ("MMO")
equip = ("D014-K-00001")
report_prio = ("1")
order_prio = ("2")
job = ("Oel wechsel")
w_time = ("120")
fte = ("2")
reason = ("Kein Oel vorhanden")
cause = ("MAR 2")
solved = ("Erledigt")
mar2_list = ([date, p_unit, equip, report_prio, order_prio, job, w_time, fte, reason, cause, solved])
cursor.execute("create table if not exists mar21 (DATE integer, P_UNIT text, EQUIP text, REPORT_PRIO text, ORDER_PRIO text, JOB text, W_TIME integer, FTE integer, REASON text, CAUSE text, SOLVED text)")
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)
the first Error:
Incorrect number of bindings supplied. The current statement uses 11, and there are 10 supplied.
File "C:\Users\andre\PycharmProjects\Wartezeiten\db_test.py", line 26, in <module>
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)
Okay i found in my search i need one more comma at the end of the Values
when i set the comma like this
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?,)", mar2_list)
i have a syntax error
near ")": syntax error
File "C:\Users\andre\PycharmProjects\Wartezeiten\db_test.py", line 26, in <module>
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?,)", mar2_list)
i think i´m running a wrong way with the "insert values" line!
since you have one record use execute instead of executemany
cursor.execute("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)

Incorrect number of bindings supplied. The current statement uses 10, and there are 11 supplied

import sqlite3 ,csv
with open("BollywoodMovieDetail.csv","r")as file:
no_records = 0
for row in file:
c.execute("INSERT INTO Movie VALUES(?,?,?,?,?,?,?,?,?,?)", row.split(","))
conn.commit()
no_records += 1
conn.close()
print('\n{} Records Transferred'.format(no_records))
i dont know why the code is terminating my guess is that their is cell which have "," in it amd cousing problem. If it is so please let me know how to fix it. I m new to SQLITE3 so its getting hectic
Your insert statement expects 10 values per record. The error message implies that one or more lines has 11 values after splitting by comma, or, alternatively, one or more lines have 10 commas. You may iterate over your file and try to find the offending line(s):
with open("BollywoodMovieDetail.csv", "r") as file:
for row in file:
parts = row.split(",")
if len(parts) == 11:
print(row)

Python3 Sqllite Normal query works but not while passing it a tuple

I have a Db from where I have to display all the columns which match the substring of the column given by user.
The following code works:
c.execute("select *from Transactions where Description like '%sh%' ")
conn.commit()
print(c.fetchall())
conn.close()
But when I try to run this code it returns me an empty list:
def search(col,val):
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("Select *from Transactions where ? Like ? ",(col,'%'+val+'%'))
print(c.fetchall())
search('description',"sh")
Also the result will always be a blank list even if the col name is wrong. as opposed the usual error which says column not found.
Please Help

adding getmtime() to db and getting TypeError: 'float' object is not iterable

I'm trying to add all the file names and last modification time for files in a specific directory to a database in two different columns. This is code I have:
def getlist (self):
dbinput = self.txt_dest.get()
conn = sqlite3.connect ('dirdrill.db')
for files in os.listdir(dbinput):
for modtime in os.path.getmtime(dbinput):
with conn:
cur = conn.cursor()
cur.execute("INSERT INTO tbl_files(col_filename, col_modinfo) values (?,?)", files, modtime)
conn.commit()
conn.close()
getinfo(self)
I am getting the following error:
File "C:\Users\Ryan\Documents\GitHub\Tech-Academy-Projects\Python\dir_drill\dirdrill_func.py", line 69, in getlist
for modtime in os.path.getmtime(dbinput):
TypeError: 'float' object is not iterable
Do I need to convert the numbers that getmtime() returns into a human friendly format so that it is not a float? If so, how? Or should I be structuring the function a different way?
EDIT:
Thanks to some other help I found out that I just needed to change one line to modinfo = os.path.getmtime(dbinput). Did that and it solved the float error. However now it says that I am offering too many arguments, max 2 and I have 3, even thought I only see two. Onto the next bug... :-)
Found the answer to the original question and the additional error I discovered.
In the original code I needed to change the following:
for modtime in os.path.getmtime(dbinput):
to:
modtime = os.path.getmtime(dbinput)
For the follow up error related to too many parameters, files and modinfo needed to be wrapped in parenthesis like so:
cur.execute("INSERT INTO tbl_files(col_filename, col_modinfo) values (?,?)", (files, modtime))
Hopes this helps anyone else experiencing the same error.

strange Oracle error: "invalid format text"

I'm trying to fetch some data from a column whose DATA_TYPE=NUMBER(1,0) with this piece of code:
import cx_Oracle
conn = cx_Oracle.connect(usr, pwd, url)
cursor = conn.cursor()
cursor.execute("SELECT DELETED FROM SERVICEORDER WHERE ORDERID='TEST'")
print(cursor.fetchone()[0])
which complains thus:
Traceback (most recent call last):
File "main.py", line 247, in <module>
check = completed()
File "main.py", line 57, in completed
deleted = cursor.fetchone()[0]
cx_Oracle.DatabaseError: OCI-22061: invalid format text [T
Replacing 'DELETED' column with one whose DATA_TYPE=VARCHAR2 does not throw such a complaint.
I am running in to this problem now using cx_Oracle 5.0.4 with Unicode support. The above accepted solution did not work for me. The DELETED column in the question is a Numeric column, which is what causes this bug.
According to the mailing list ( http://comments.gmane.org/gmane.comp.python.db.cx-oracle/2390 ) it may be a bug in Oracle that shows only in cx_Oracle with Unicode support.
from the link:
"When I build cx_Oracle without Unicode support, it all works as expected.
When I build cx_Oracle with Unicode support, attempting to use a query
that returns a numeric value (such as):
con = Connection( ... )
cur = con.cursor()
cur.execute( 'SELECT 1 FROM DUAL' )
rows = cur.fetchall()
results in this exception:
cx_Oracle.DatabaseError: OCI-22061: invalid format text [T
"
What I did to work around it, is on the select statement, do:
cur.execute( 'SELECT to_char(1) FROM DUAL' )
rows = cur.fetchall()
for row in rows:
val = int(row[0])
It's pretty ugly, but it works.
These types of errors went away when I upgraded to cx_Oracle 5.1. If the RPM doesn't install (like it happened for me on Red Hat 5.5) then you can usually rpm2cpio the file, take the cx_Oracle.so and put it into your python site-packages directory.
A work-around is putting time.sleep(1) before cursor.fetchone():
...
cursor.execute("SELECT DELETED FROM SERVICEORDER WHERE ORDERID='TEST'")
time.sleep(1)
print(cursor.fetchone()[0])
I had the same error.
Commit helped me:
conn = cx_Oracle.connect(...)
...
cursor.execute()
conn.commit()

Resources