I am trying to create a table in sqlite with some data in a .txt file. I am using python, and this is my code:
import sqlite3
conn = sqlite3.connect('TEST_Inventory.sqlite')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS InventoryData''')
cur.execute('''
CREATE TABLE `InventoryData` (
`INV_ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`Inventory_Name` TEXT)''')
fname = ('NameINV.txt')
fh = open(fname)
for line in fh:
name = line.split()
print name
cur.execute('''INSERT INTO InventoryData (Inventory_Name)
VALUES ( '?' )''', (name,))
cur.commit()
However, every time I try to run this code I get this error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
What exactly is going on here?
Sql statements can be constructed in 2 ways.
By concatenating string (unsafe, easy for sql injection attacks) ex: sql_string = 'INSERT INTO TABLE_1 (COL1, COL2) VALUES(\\'' + value1 + '\\',\\'' + value2 + '\\')'
By using placeholders and bind variables (recommended) ex: sql_string = 'INSERT INTO TABLE_1(COL1,COL2) VALUES (?,?)'
and supply bind variables as (value1,value2)
When you use bind variables, there is no need to quote them (to identify them as string/text data). Bind variables will be substituted at database, during execution of statement.
To answer precisely, when you use single-quote around placeholder '?'
, it will be treated as a text and program doesn't know where to bind the data you supplied while executing query. Just use ?
without quotes, so that, parser finds placeholders to substitute with data and code will execute.
cur.execute('''INSERT INTO InventoryData (Inventory_Name)
VALUES ( ? )''', (name,))
Don't quote the placeholder; quoting is taken care of by the database driver when replacing the placeholder with the value:
cur.execute('''INSERT INTO InventoryData (Inventory_Name)
VALUES ( ? )''', (name,))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.