Inserting tuple's elements to database - python

I have a tuple that i wanna store its elements, I'm trying to insert it as following and it gives the following error, what am i doing wrong ? records_to_be_inserted is the tuple that has 8 elements.
with self.connection:
cur = self.connection.cursor()
cur.executemany("INSERT INTO rehberim(names, phone, mobile, email, \
photo, address, note, date) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", self.records_to_be_inserTed)
Traceback (most recent call last):
File "/home/tayfun/workspace/personal_guide/modules/mainwindow.py", line 57, in save_records
photo, address, note, date) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", self.records_to_be_inserTed)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 8, and there are 0 supplied.

Note that the executemany is for inserting multiple rows, e.g.,
import sqlite3
""" the table structure is:
create table tab
a char(1),
b char(2),
c char(3)
)
"""
conn = sqlite3.connect('C:\\test.db')
stmt = "insert into tab (a, b, c) values (?, ?, ?)"
cur = conn.cursor()
## many rows
vals = [('1','2','3'), ('2','3','4'), ('3','4','5')]
cur.executemany(stmt, vals)
cur.close()
This will result in three rows in the database. If it is because you have multiple values in one query, you need to format it!
Edit: Added formatting with dictionaries
By using the following approach you do not need to consider the order of the values in the format call because the key in the dictionary is mapping the value into the {key_word} placeholder.
values = {'a' : 'value_a',
'b' : 'value_b'}
stmt = "insert into tab (col_a, col_b) values ({a}, {b})".format(**values)

The query must have all the data ready to be inserted.
You are calling a function in the query, which i guess you want that provides the data but that wont work.
You need to pass all the data in variables or locate them in the tuple index (like: tuple_name[1], tuple_name[4], etc.)
Example:
myTuple = ['a','b','c','d','e','f','g']
cur.executemany("INSERT INTO rehberim(names, phone, mobile, email, \
photo, address, note, date) VALUES({0}, {1}, {2}, {3}, {4}, {5}, {6}" .format (myTuple[1], myTuple[2], myTuple[3], myTuple[4], myTuple[5], myTuple[6], myTuple[7])

Related

Python and SQLite3 ProgrammingError: Incorrect number of bindings supplied. The current statement uses 10, and there are 1 supplied

I am trying to load a csv file into my database table and keep getting this ProgrammingError: Incorrect number of bindings supplied. The current statement uses 10, and there are 1 supplied. I think it may have something to do with my c.execute but am unsure what the fix would be. I attached my code below for trying to insert the CSV into my single table.
My code is
import sqlite3
import csv
# creating my first database that will be used for the assignment.
conn = sqlite3.connect('Assignment3.db')
c = conn.cursor()
#Creating table- CCSubset with all of the required fields
c.execute("drop table if exists CCSubset")
c.execute("""CREATE TABLE CCSubset (
CCSubset_id integer not null primary key,
CCSubset_limit int,
CCSubset_sex varchar(10),
CCSubset_edu varchar(10),
CCSubset_marr varchar(10),
CCSubset_age int,
CCSubset_pay int,
CCSubset_bill int,
CCSubset_payamt int,
CCSubset_default int)""")
conn.commit()
f=open('CCSubset.csv')
insert sql = "insert into CCSubset values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
for row in str(csv.reader(f)):
c.execute(insert_sql, row)
The error I receive is: ProgrammingERROR: Incorrect number of binding supplied. The current statement uses 10, and there are 1 supplied.
Here is the updated code:
# creating my first database that will be used for the assignment.
conn = sqlite3.connect('Assignment3.db')
c = conn.cursor()
#Creating table- CCSubset with all of the required fields
c.execute("drop table if exists CCSubset")
c.execute("""CREATE TABLE CCSubset (
CCSubset_id integer not null primary key,
CCSubset_limit int,
CCSubset_sex varchar(10),
CCSubset_edu varchar(10),
CCSubset_marr varchar(10),
CCSubset_age integer,
CCSubset_pay int,
CCSubset_bill int,
CCSubset_payamt int,
CCSubset_default int)""")
conn.commit()
f=open('CCSubset.csv')
for row in str(reader):
insert_sql = "insert into CCSubset values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
print(row)
conn.commit()
The output I receive now is:
<
c
s
v
.
D
i
c
t
R
e
a
d
e
r
o
b
j
e
c
t
a
t
0
x
7
f
9
b
c
8
0
7
2
4
e
0
>
​
So I am at a complete stand still and don't know what I need to do. Any and all help would be appreciated.
Now I see your problem. You are converting the list that csv.reader() gives you to a string. Another time you were using the DictReader from csv. You just need the result from csv.reader() like this:
with open(CCSubset.csv) as csvfile:
filereader = csv.reader(csvfile)
for row in filereader:
c.execute(insert_sql, row)

sqlite3 - Incorrect number of bindings

I'm getting this Sqlite3 programming error: sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 0 supplied.
I'm not sure why. I have tried everything I can think of. Please assist.
Thanks!
import csv
import sqlite3
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
employees = csv.reader(open("employees.csv", "rU"))
#c.execute("CREATE TABLE employees (firstname TEXT, lastname TEXT)")
c.executemany("INSERT INTO employees(firstname, lastname) values (?, ?)", employees)
c.executemany("INSERT INTO employees(firstname, lastname) values (?, ?)", employees)
You have two ?, but supplied only with employees => values (?, ?)", employees)
csv.reader yields a generator expression. Thus, you need to caste the result as a list:
c.executemany("INSERT INTO employees(firstname, lastname) values (?, ?)", list(employees))
employees needs to be a 2d list, some for each call of executemany. You can create is easily using a nested list comprehensions:
import csv
import sqlite3
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
reader = csv.reader(open("employees.csv", "rU"))
employees = [[x for x in row] for row in reader]
c.executemany("INSERT INTO employees(firstname, lastname) values (?, ?)", employees)

retrieving data from one table and putting into another PYTHON SQL

Trying to take a piece of data from at table in the database and inserting it into another table:
Fetching the order total and assigning it to variable:
cursor.execute('''SELECT Price FROM Tracks WHERE TrackID = ?''', (trackChoice,))
ordertotal = str(cursor.fetchall())
Putting it into table:
cursor.execute('''INSERT INTO Orders(OrderID, Date, OrderTotal, CustomerID, TrackID) VALUES(?, ?, ?, ?, ?)''', (orderID, date,
ordertotal, customerID, trackChoice))
Error:
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.
With cursor.fetchall() you get all the rows in 'Tracks'. So it will have an ID and probably other informations as well. f.E. something like this: (1, 'William', 'Shakespeare', 'm', None, '1961-10-25'). What is 'ordertotal'? I guess it will be a number? If yes, and you are using sqlite3 you could use row_factory. See the answere here for more information: Get a list of field values from Python's sqlite3, not tuples representing rows
Why not just do:
cursor.execute("""
INSERT INTO Orders(name, Date, name, name, name)
VALUES(?, strftime('now'), ?, ?, ?)""",
(value, value, value, value);
That is, use the current time in the database.
(I assume that name is really four different columns or you should get another error.)

Inserting multiple list into SQLite database using Python 3

I have multiple list and i would like to insert the data that is stored in the list into the sqlite database.
My insert statement is:
c.executemany("INSERT INTO admin(class, level, registerNo, ic, name) VALUES(?, ?, ?, ?, ?)", (sclass, level, registerNo, ic, name))
But my error stated:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 10 supplied.

Pass variable into SQLAlchemy query

Trying to pass a variable (a set) into an sqlalchemy query.
Found this: How can I bind a list to a parameter in a custom query in sqlalchemy? But it requires you to know many items there are. The number of entries changes at any given moment.
My previous question went mostly unanswered unfortunately so I figured I'd re-iterate what I'm trying to do here.
Basically, I have this variable: sites = set(db1).intersection(db2) and I'm trying to pass it into this sql alchemy query:
'test': DBSession.query(A_School.cis_site_id.in_(sites)).all(),
But I get invalid syntax errors and invalid parameter type errors...I can't get this thing to do what I want it to do. DB1 and DB2 are, as you mightve guessed, 2 different databases.
db1 = cis_db.query(site.site_id).join(site_tag).filter(site_tag.tag_id.like(202)).all()
db2 = DBSession.query(A_School.cis_site_id).all()
Full error:
ProgrammingError: (ProgrammingError) ('Invalid parameter type. param-index=0 param-type=KeyedTuple', 'HY105') u'SELECT [A_School].cis_site_id IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) AS anon_1
FROM [A_School]' ((14639,), (14709,), (14587,), (14966,), (14625,), (14589,), (15144,), (15171,) ... displaying 10 of 18 total bound parameter sets ... (15133,), (14036,))
KeyedTuple is the type of each row returned by SQLAlchemy when not querying one full model. You are making sets of keyed tuples, rather than sets of the single value in each tuple. Should look something like this instead:
db1 = set(x.site_id for x in cis_db.query(site.site_id).join(site_tag).filter(site_tag.tag_id.like(202)))
db2 = set(x.cis_site_id for x in DBSession.query(A_School.cis_site_id))
sites = db1.intersection(db2)
test = DBSession.query(A_School).filter(A_School.cis_site_id.in_(sites)).all()
Assuming you would like to load schools for the sites, how about you try:
DBSession.query(A_School).filter(A_School.cis_site_id.in_(sites)).all()
instead of:
DBSession.query(A_School.cis_site_id.in_(sites)).all()

Categories