Insert values from list into sqlite3 database - python

I try to insert values from variables and values from a list into a sqlite3 database.
Problem: The list is not unpacked, it is used as a single element. What do I miss? Do I have to unpack the list into variables? In the example list_element is a list with six elements
cur.execute("INSERT INTO websites VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
('NULL', qry, strtm, list_element, COUNTER, SPAM, EXCERPT, COLLECTION))

Concatenate the sequences:
cur.execute("INSERT INTO websites VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
[None, qry, strtm] + list_element + [COUNTER, SPAM, EXCERPT, COLLECTION])
I built a list here as it is easier to concatenate lists and lists than it is to concatenate tuples and lists (you'd have to convert list_element to a tuple first).
Note that I used None instead of 'NULL'; None is translated to a SQL NULL by Python database adapters.

Related

Workaround for the ? of sqlite3.Cursor instance

I have a table with 16 columns and I would like to replace the syntax of the executemany method, which is:
# DATABASE is of type sqlite3.Cursor
# data is of type List[List]
DATABASE.executemany(
"INSERT INTO table_name VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", data
)
DATABASE_CONNECTION.commit()
with something more compact. I don't want to repeat the question mark 16 times. Is there a solution for this ?
You can construct the sql statement lik ethis:
sql = "INSERT INTO table_name VALUES (" + ("?," * len(data)).strip(",") + ")"
so that you get "?," repeated as many times as the number of items in data and use it:
DATABASE.executemany(sql, data)

Python SQLite Delete From Where multiple values match

I need to delete entries in my SQLite DB where all Values match.
So I create the entry like that:
# Insert a row of data
c.execute("insert into Database (Value1, Value2, Value3, Value4, Value5, Value6) values (?, ?, ?, ?, ?, ?)",
(d1, d2, d3, d4, d5, d6))
And later on i will delete the exact entry by its values. I tried it like that:
c.execute("delete from Database where (Value1, Value2, Value3, Value4, Value5, Value6) values (?, ?, ?, ?, ?, ?)",
("String1", "String2", "String3", "String4", "String5", "String6"))
But i get this: OperationalError: near "values": syntax error
How do I delete a SQLite entry with multiple values matching?
You have to write the full SQL condition:
c.execute('delete from Database where Value1=? and Value2=? and Value3=? and Value4=? and Value5=? and Value6=?', ("String1", "String2", "String3", "String4", "String5", "String6"))
You can learn the full syntax here.

Why is this sqlite3 UPDATE giving a syntax error?

I have a function that drops some tables and reinitializes a new set which are working fine, then when it updates the existing table with the following:
self.cursor.execute('''UPDATE beers1 SET (beer_name, og, fg, beer_desc, ibu, glass_type, keg_size)
VALUES (?,?,?,?,?,?,?) where id=1''',("Beer", 1, 1, "Delicious!", 0, "Pint Glass", 640))
Which then gives me:
OperationalError: near "(": syntax error
Any insight would be incredibly helpful. Thanks!
The standard SQL syntax for an UPDATE statement is either:
UPDATE beers1
SET (beer_name, og, fg, beer_desc, ibu, glass_type, keg_size) =
(?, ?, ?, ?, ?, ?, ?)
WHERE id = 1
Or:
UPDATE beers1
SET beer_name = ?, og = ?, fg = ?,
beer_desc = ?, ibu = ?, glass_type = ?, keg_size = ?
WHERE id = 1
You will need to check the SQLite3 manual to see which is supported by SQLite3. The second is almost guaranteed to be supported; the first may not be.

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

Inserting tuple's elements to database

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

Categories