python sqlite3 parameterization - insert throws no such column error - python

Insert in columns with parameterized query throws no such column error
First (working) example:
# unit test input
name = "issue_number_1"
text = "issue_text"
rating_sum = 0
if name:
# check if issue is already in db
with self.conn: # this should release the connection when finished
test = cursor.execute("SELECT name, text FROM issue WHERE name = ?", (name,))
data = test.fetchall()
print(data)
this is working and prints:
[('issue_number_1', 'issue_text')]
Second (non working) example:
# unit test input
name = "issue_number_2"
text = "issue_text"
rating_sum = 0
if name:
with self.conn:
sql_string = "INSERT INTO issue (name, text, rating_sum) VALUES (name = ?, text = ?, rating_sum = ?)"
cursor.execute(sql_string, (name, text, rating_sum,))
throws this error:
cursor.execute(sql_string, (name, text, rating_sum,))
sqlite3.OperationalError: no such column: name
the column name exists, the first example proofed that
the name: "issue_number_2" does not exist in the DB
the second example fails exactly same with only name to insert (only one parameter)
i had no problems inserting with string concatenation so the problem should be in my second example code somewhere

You need to add single quote.for example:
"INSERT INTO table (field) VALUES ('$1')"
add just values in second () and add single quote around string values.

After a lot of experiments i was a little bit confused....
This is the right syntax:
sql_string = "INSERT INTO issue (name, text, rating_sum) VALUES (?, ?, ?)"
cursor.execute(sql_string, (name, text, rating_sum,))

The statement:
INSERT INTO .... VALUES ....
is an SQL statement and the correct syntax is:
INSERT INTO tablename (col1, col2, ...) VALUES (expr1, expr2, ...)
where col1, col2, ... are columns of the table tablename and expr1, expr2, ... are expressions or literals that are evaluated and assigned to each of the columns col1, col2, ... respectively.
So the syntax that you use is not valid SQL syntax.
The assignment of the values is not performed inside VALUES(...).
The correct syntax to use in Python would be:
INSERT INTO issue (name, text, rating_sum) VALUES (?, ?, ?)

Related

SQLlite3 Insert values to columns based on Where condition

I'm trying to insert values to new columns only for rows which answer a specific where condition (when a the value in Name column is equal to a given name).
This is the code I've written so far:
cours.execute("""INSERT INTO NewTable(Straight, Right, Left) WHERE Name = (?)
VALUES (?, ?, ?) """,
(name, DIRECTIONS['straight'], DIRECTIONS['right'], DIRECTIONS['left']))
conn.commit()
after I do the commit I get the following error:
sqlite3.OperationalError: near "WHERE": syntax error
Thanks.
Try with an UPDATE statement:
cours.execute("""UPDATE NewTable
SET Straight = ?, Right = ?, Left = ?
WHERE Name = ?""",
(DIRECTIONS['straight'], DIRECTIONS['right'], DIRECTIONS['left'], name))

Set Sqlite query results as variables [duplicate]

This question already has answers here:
How can I get dict from sqlite query?
(16 answers)
Closed 4 years ago.
Issue:
Hi, right now I am making queries to sqlite and assigning the result to variables like this:
Table structure: rowid, name, something
cursor.execute("SELECT * FROM my_table WHERE my_condition = 'ExampleForSO'")
found_record = cursor.fetchone()
record_id = found_record[0]
record_name = found_record[1]
record_something = found_record[2]
print(record_name)
However, it's very possible that someday I have to add a new column to the table. Let's put the example of adding that column:
Table structure: rowid, age, name, something
In that scenario, if we run the same code, name and something will be assigned wrongly and the print will not get me the name but the age, so I have to edit the code manually to fit the current index. However, I am working now with tables of more than 100 fields for a complex UI and doing this is tiresome.
Desired output:
I am wondering if there is a better way to catch results by using dicts or something like this:
Note for lurkers: The next snipped is made up code that does not works, do not use it.
cursor.execute_to(my_dict,
'''SELECT rowid as my_dict["id"],
name as my_dict["name"],
something as my_dict["something"]
FROM my_table WHERE my_condition = "ExampleForSO"''')
print(my_dict['name'])
I am probably wrong with this approach, but that's close to what I want. That way if I don't access the results as an index, and if add a new column, no matter where it's, the output would be the same.
What is the correct way to achieve it? Is there any other alternatives?
You can use namedtuple and then specify connection.row_factory in sqlite. Example:
import sqlite3
from collections import namedtuple
# specify my row structure using namedtuple
MyRecord = namedtuple('MyRecord', 'record_id record_name record_something')
con = sqlite3.connect(":memory:")
con.isolation_level = None
con.row_factory = lambda cursor, row: MyRecord(*row)
cur = con.cursor()
cur.execute("CREATE TABLE my_table (record_id integer PRIMARY KEY, record_name text NOT NULL, record_something text NOT NULL)")
cur.execute("INSERT INTO my_table (record_name, record_something) VALUES (?, ?)", ('Andrej', 'This is something'))
cur.execute("INSERT INTO my_table (record_name, record_something) VALUES (?, ?)", ('Andrej', 'This is something too'))
cur.execute("INSERT INTO my_table (record_name, record_something) VALUES (?, ?)", ('Adrika', 'This is new!'))
for row in cur.execute("SELECT * FROM my_table WHERE record_name LIKE 'A%'"):
print(f'ID={row.record_id} NAME={row.record_name} SOMETHING={row.record_something}')
con.close()
Prints:
ID=1 NAME=Andrej SOMETHING=This is something
ID=2 NAME=Andrej SOMETHING=This is something too
ID=3 NAME=Adrika SOMETHING=This is new!

Python sqlite3 - operationalerror near "2017"

I'm new to programming. I have dictionary called record, that receives various inputs like 'Color', 'Type' 'quantity',etc. Now I tried to add a Date column then insert into sqlite table running through the 'if loop' with the code below. But I get an "Operational error near 2017", ie near the date.
Can anyone help please? Thanks in advance
Date = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d'))
record['Date'] = Date
column = [record['Color'], Date]
values = [record['quantity'], record['Date']]
column = ','.join(column)
if record['Type'] == 'T-Shirts' and record['Style'] == 'Soft':
stment = ("INSERT INTO xtrasmall (%s) values(?)" %column)
c.execute(stment, values)
conn.commit()
Updated
You can simplify the code as follows:
from datetime import datetime
date = datetime.now().date()
sql = "INSERT INTO xtrasmall (%s, Date) values (?, ?)" % record['Color']
c.execute(sql, (record['quantity'], date))
This substitutes the value of the selected color directly into the column names in the query string. Then the query is executed passing the quantity and date string as arguments. The date should automatically be converted to a string, but you could convert with str() if desired.
This does assume that the other colour columns have a default value (presumably 0), or permit null values.
Original answer
Because you are constructing the query with string interpolation (i.e. substituting %s for a string) your statement becomes something like this:
INSERT INTO xtrasmall (Red,2017-10-06) values(?)
which is not valid because 2017-10-06 is not a valid column name. Print out stment before executing it to see.
If you know what the column names are just specify them in the query:
values = ['Red', 2, Date]
c.execute("INSERT INTO xtrasmall (color, quantity, date) values (?, ?, ?)", values)
conn.commit()
You need to use a ? for each column that you are inserting.
It looks like you want to insert the dictionary using its keys and values. This can be done like this:
record = {'date':'2017-10-06', 'color': 'Red', 'quantity': 2}
columns = ','.join(record.keys())
placeholders = ','.join('?' * len(record.values()))
sql = 'INSERT INTO xtrasmall ({}) VALUES ({})'.format(columns, placeholders)
c.execute(sql, record.values())
This code will generate the parameterised SQL statement:
INSERT INTO xtrasmall (date,color,quantity) VALUES (?,?,?)
and then execute it using the dictionary's values as the parameters.

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

How to add multiple Columns into Sqlite3 from a for loop in Python

Admittedly I a still very new to both Python and Sqlite3, and I am attempting to add the contents of two lists into a database so that one list is in the first column and the second list shows up in the second column. To this point, I have been unsuccessful. I am defenitely making a fundamental error, and the error message that I get is this: "sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type."
my code is this:
import sqlite3
names = ['Tom', 'Dick', 'Harry']
ids = ['A452', 'B698', 'Kd9f']
conn = sqlite3.connect('testforinput.db')
c = conn.cursor()
c.execute("CREATE TABLE thetable(name TEXT, id TEXT)")
index = 0
for link in names:
idofperson = ids[index]
c.execute("INSERT INTO thetable(name, id)VALUES(?, ?)", ( [link], idofperson ))
index+=1
conn.commit()
conn.close()
The error occurs because of the for loop specifically the "idofperson" variable
The desired outcome is that I would like to have two columns created in sql one being name and the other being id.
Any help would be greatly appreciated.
I think you just change
index =0
for link in names:
idofperson = ids[index]
c.execute("INSERT INTO thetable(name, id)VALUES(?, ?)", ( [link], idofperson ))
to this (use enumrate and change [list] to list, because you pass a list into a column need TEXT type):
for index, link in enumrable(names):
idofperson = ids[index]
c.execute("INSERT INTO thetable(name, id)VALUES(?, ?)", ( link, idofperson ))
your variable index is not increasing.try using the enumerate on for loop. or just add index += 1 after execute
the error is occurring because of the unsupported data type you are trying to push in, you can't store list as it is, you need to change to another supported data types, i like this solution ....it worked for me https://stackoverflow.com/a/18622264/6180263
for your problem, try this:
import sqlite3
names = ['Tom', 'Dick', 'Harry']
ids = ['A452', 'B698', 'Kd9f']
data = zip(names, ids)
conn = sqlite3.connect('testforinput.db')
c = conn.cursor()
c.execute("CREATE TABLE thetable(name TEXT, id TEXT)")
for d in data:
sql = "INSERT INTO thetable (name, id) VALUES ('%s', '%s'); " % d
c.execute(sql)
conn.commit()
conn.close()
I suggest change data to a list of dict, like this [{'name':'Tom', 'id': 'A452'}, {'name':'dick', 'id':'B698'}..]
and you can generate insert sql by data, this make the insert more flexible.

Categories