Updating SQL with Python - Incorrect number of bindings - python

I keep getting this error
Traceback (most recent call last):
File "test.py", line 7, in <module>
c.execute("INSERT INTO file_routes (file_route) VALUES (?)", (file_route))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.
I create the table with this
createTable_filenames = """
CREATE TABLE IF NOT EXISTS
file_routes(
routes_id INTEGER PRIMARY KEY,
file_route TEXT
)
"""
This is the code I am trying to run and it doesn't work
import sqlite3
conn = sqlite3.connect('fantasyresults.db')
c = conn.cursor()
file_route = "test"
c.execute("INSERT INTO file_routes (file_route) VALUES (?)", (file_route))
conn.commit()
I don't understand why this code works, I set up the structure the same way.
c.execute than ("INSERT INTO <tablename> (<column id>) VALUES (?)", (<variable>))
c.execute("INSERT INTO draftkings (account_id, sport, game_type, entry_key, entry_name, opponent, contest_key, contest_date, position, points, winnings, winnings_tickets, contest_entries, entry_fee, prize_pool, places_paid)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (account_id, sport, game_type, entry_key, entry_name, opponent, contest_key, contest_date, position, points, winnings, winnings_tickets, contest_entries, entry_fee, prize_pool, places_paid))
Any help is much appreciated, I don't know what I am not seeing here.

The problem is that it is considering the parameter as string instead of tuple as that's the expected behavior in python for a tuple with single element.
Try updating the parameter tuple as
(file_route, )
have a comma after the parameter.

Related

Sqlite3 error 2 arguments given (7given) when finding data

def addPersonRec(Firstname, Surname, DoB, Age, Notes, DateCreated):
con=sqlite3.connect("silver.db")
cur = con.cursor()
cur.execute("INSERT INTO silver VAULES (NULL, ?, ?, ?, ?, ?, ?)", Firstname, Surname, DoB, Age, Notes, DateCreated)
con.commit()
con.close()
so my issue is i have improted sqlite 3 and when i run it i get this error line 14, in addPersonRec
cur.execute("INSERT INTO silver VAULES (NULL, ?, ?, ?, ?, ?, ?)",Firstname, Surname, DoB, Age, Notes, DateCreated)
TypeError: function takes at most 2 arguments (7 given) please any ideas help
.execute's second argument should be a tuple.
Also note that you have a typo. VAULES should be VALUES.
cur.execute("INSERT INTO silver VALUES (NULL, ?, ?, ?, ?, ?, ?)",
(Firstname, Surname, DoB, Age, Notes, DateCreated))

how to insert variable in sqlite3 request python

Dears,
how can I check if pos_cli from database is equal to variable pos_id? for now with code below I get the following error
cur.execute("CREATE TABLE IF NOT EXISTS Magnit_Coor (pos_cli INTEGER PRIMARY KEY, lat INTEGER, long INTEGER);")
cur.execute('SELECT * FROM Magnit_pos')
data = cur.fetchall()
while True:
for coo in data:
full_add = coo[6:11]
pos_id = coo[0]
print (pos_id)
yand_add = ", ".join(full_add)
g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_Coor WHERE pos_cli = (?))',pos_id)
g = cur.fetchone()[0]
error below
10001
Traceback (most recent call last):
File "geoco.py", line 17, in <module>
g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_pos WHERE pos_cli = (?))',pos_id)
ValueError: parameters are of unsupported type
The initial code to create Magnit_pos table and pos_cli especially below
cur.execute("DROP TABLE IF EXISTS Magnit_Pos;")
cur.execute(
"CREATE TABLE Magnit_Pos (pos_cli INTEGER PRIMARY KEY, magnit_name TEXT, codesfa TEXT, codewsot TEXT, pos_sap TEXT, source_dc TEXT, zip TEXT, region TEXT, area TEXT, city TEXT, street TEXT, house TEXT, build TEXT);")
with open('magnit.csv') as csvfile:
magnit = csv.reader(csvfile, delimiter=';')
print(magnit)
for row in magnit:
print(row[0])
# to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8")]
cur.execute("INSERT INTO Magnit_Pos (pos_cli, magnit_name, codesfa, codewsot, pos_sap, source_dc, zip, region, area, city, street, house, build) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", row)
From python's sqlite3 documentation (emphasis mine):
Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method.
So you should be using:
g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_Coor WHERE pos_cli = (?))',(pos_id,))

Python - SQLite : Update two record with same identify value

i have a script like below :
import psutil
import sqlite3
DISK = {'1': ['C:\\', 'C:\\', 'NTFS', 'rw,fixed', '75.0Gb', '54.0Gb', '20.0Gb', '72.2%'], '2': ['D:\\', 'D:\\', 'NTFS', 'rw,fixed', '399.0Gb', '208.0Gb', '191.0Gb', '52.2%']}
conn = sqlite3.connect("Test.db")
c = conn.cursor()
result = c.execute("SELECT * FROM clientinfo WHERE IP = ?", ("192.168.10.111",))
if (len(result.fetchall()) > 0):
for x in DISK :
c.execute("UPDATE disk SET Device = ?, 'Mount Point' = ?, 'fstyle' = ?, 'opts' = ?, 'total' = ?, 'used' = ?, 'free' = ?, 'percent' = ? WHERE Client_IP = ?", (DISK[x][0], DISK[x][1], DISK[x][2], DISK[x][3], DISK[x][4], DISK[x][5], DISK[x][6], DISK[x][7], "192.168.10.111"))
else :
for x in DISK :
c.execute("INSERT INTO disk('Client_IP', 'Device', 'Mount Point', 'fstyle', 'opts', 'total', 'used', 'free', 'percent') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ("192.168.10.111", DISK[x][0], DISK[x][1], DISK[x][2], DISK[x][3], DISK[x][4], DISK[x][5], DISK[x][6], DISK[x][7]))
conn.commit()
conn.close()
Script will check in db if there is any record about IP "192.168.10.111". If db already have record about IP "192.168.10.111", Script will update data from dict DISK to table disk of db.
If db don't have record about IP "192.168.10.111", Script will create record to insert **DISK"" to database.
INSERT command work well but the UPDATE command don't work like i want. After INSERT command run, in table disk i will have two record about disk C and disk D with same value of column Client_IP (192.168.10.111).
After UPDATE, two record of IP "192.168.10.111" get same value on every column ehich is very wrong. One record must be contain information about disk C and another record cotain disk D information.
How can i make the UPDATE work right ? length of dict DISK depend on how many mounted devices the computer has. So i need to use for loop to UPDATE but not static UPDATE.
Please tell me how to fix this,
Many thanks,
Francis
Your SELECT query column value is incorrect based on your UPDATE and INSERT queries later on. Instead of IP, should't it be CLIENT_IP? Also, you need to change your string query formatting. Remove the single quotes form your column names. Lastely, you can shorten your code by using a simple list comprehension and cursor.executemany:
import sqlite3
DISK = {'1': ['C:\\', 'C:\\', 'NTFS', 'rw,fixed', '75.0Gb', '54.0Gb', '20.0Gb', '72.2%'], '2': ['D:\\', 'D:\\', 'NTFS', 'rw,fixed', '399.0Gb', '208.0Gb', '191.0Gb', '52.2%']}
conn = sqlite3.connect("Test.db")
c = conn.cursor()
if not list(c.execute('SELECT * FROM lientinfo WHERE CLIENT_IP = ?', ("192.168.10.111",))):
c.executemany("INSERT INTO disk (Client_IP, Device, Mount Point, fstyle, opts, total, used, free, percent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", [["192.168.10.111", *i] for i in DISK.values()])
else:
c.executemany('UPDATE disk SET Device = ?, Mount Point = ?, fstyle = ?, opts = ?, total = ?, used = ?, free = ?, percent = ? WHERE Client_IP = ?', [[*i, "192.168.10.111"] for i in DISK.values()])

SQLite3 and python not inserting rows

I'm trying to insert a row into my table. I've been following the documentation here: https://docs.python.org/2/library/sqlite3.html I get the error: sqlite3.OperationalError: no such column: asd. asd is the value i entered for scholarship name. Heres my code:
conn = sqlite3.connect('pathfinder.db')
c = conn.cursor()
c.execute("INSERT INTO %s VALUES (%s, %s, %s, %s, %s, %s, %s)" % (table, request.form['scholarship_name'],request.form['scholarship_gpa'],request.form['scholarship_amount'], "Male",request.form['specific_essay'], "[]","[]"))
Consider parameterization which is advised in the very link you are following:
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
String interpolated SQL statements especially with user input from flask requests can potentially be dangerous to your database. Therefore, consider using the second argument of execute that binds values to placeholders, ?, in prepared statement.
# PREPARED STATEMENT
sql = "INSERT INTO {} VALUES (?, ?, ?, ?, ?, ?, ?)".format(table)
# QUERY EXECUTION
c.execute(sql, (request.form['scholarship_name'],
request.form['scholarship_gpa'],
request.form['scholarship_amount'],
"Male",
request.form['specific_essay'],
"[]",
"[]")
)

"Incorrect number of bindings supplied" cPython 3.5 SQLite3 VS15

import csv
import sqlite3
fileName = 'australianpublicholidays.csv'
accessMode = 'r'
# Create a database in RAM
holidayDatabase = sqlite3.connect(':memory:')
# Create a cursor
c = holidayDatabase.cursor()
# Create a table
c.execute('''CREATE TABLE holidays
(date text, holidayName text, information text, moreInformation text, applicableTo text)''')
# Read the file contents in to the table
with open(fileName, accessMode) as publicHolidays :
listOfPublicHolidays = csv.reader(publicHolidays)
for currentRow in listOfPublicHolidays :
for currentEntry in currentRow :
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentEntry)
# Close the database
holidayDatabase.close()
The following line
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentEntry)
is causing this error
Incorrect number of bindings supplied. The current statement uses 5,
and there are 4 supplied.
currentRow is already a sequence. It's a list of all of the fields in the row.
If you were to print out currentRow, you'd get output like this (assuming this is your data set https://data.gov.au/dataset/australian-holidays-machine-readable-dataset):
['Date', 'Holiday Name', 'Information', 'More Information', 'Applicable To']
['20150101', "New Year's Day", "New Year's Day is the first day of the calendaryear and is celebrated each January 1st", '', 'NAT']
['20150126', 'Australia Day', 'Always celebrated on 26 January', 'http://www.australiaday.org.au/', 'NAT']
['20150302', 'Labour Day', 'Always on a Monday, creating a long weekend. It celebrates the eight-hour working day, a victory for workers in the mid-late 19th century.',http://www.commerce.wa.gov.au/labour-relations/public-holidays-western-australia', 'WA']
...
When you do
for currentEntry in currentRow :
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentEntry)
You're actually getting a list of all of the characters in the first element in the list.
Because you didn't skip the header row, you're actually getting a list of the characters in the word "Date". Which equals 4 characters and is causing the error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current sta
tement uses 5, and there are 4 supplied.
If you were to skip the header line using next(listOfPublicHolidays, None) as in:
with open(fileName, accessMode) as publicHolidays :
listOfPublicHolidays = csv.reader(publicHolidays)
next(listOfPublicHolidays, None)
for currentRow in listOfPublicHolidays :
for currentEntry in currentRow :
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentEntry)
you would get the following error message because currentEntry would be a list of the characters in "20150101", having a length of 8:
Traceback (most recent call last):
File "holidaysorig.py", line 25, in <module>
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', tuple(currentEntry)
)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 8 supplied.
That's why it works (for the most part) when you remove the for currentEntry in currentRow : block and rewrite it as:
import csv
import sqlite3
fileName = 'australianpublicholidays.csv'
accessMode = 'r'
# Create a database in RAM
holidayDatabase = sqlite3.connect(':memory:')
# Create a cursor
c = holidayDatabase.cursor()
# Create a table
c.execute('''CREATE TABLE holidays
(date text, holidayName text, information text, moreInformation text, applicableTo text)''')
# Read the file contents in to the table
with open(fileName, accessMode) as publicHolidays :
listOfPublicHolidays = csv.reader(publicHolidays)
for currentRow in listOfPublicHolidays :
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentRow)
# Close the database
holidayDatabase.close()
NOTE: On my machine, I got the following errors:
(holidays) C:\Users\eyounjo\projects\holidays>python holidaysorig.py
Traceback (most recent call last):
File "holidaysorig.py", line 22, in <module>
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentRow)
sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.
So I rewrote your script as the following to deal with the above:
import csv, codecs
import sqlite3
# Encoding fix
def latin_1_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('latin-1')
fileName = 'australianpublicholidays.csv'
accessMode = 'r'
# Create a database in RAM
holidayDatabase = sqlite3.connect(':memory:')
# Create a cursor
c = holidayDatabase.cursor()
# Create a table
c.execute('''CREATE TABLE holidays
(date text, holidayName text, information text, moreInformation text, applicableTo text)''')
# Read the file contents in to the table
# Encoding fix
with codecs.open(fileName, accessMode, encoding='latin-1') as publicHolidays :
listOfPublicHolidays = csv.reader(latin_1_encoder(publicHolidays))
# Skip the header row
next(listOfPublicHolidays, None)
entries = []
for currentRow in listOfPublicHolidays:
# Work-around for "You must not use 8-bit bytestrings" error
entries.append(tuple([unicode(field, 'latin-1') for field in currentRow]))
c.executemany('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', entries)
# Close the database
holidayDatabase.close()
I have corrected the error by removing the nested for loop
Replaced the following
# Read the file contents in to the table
with open(fileName, accessMode) as publicHolidays :
listOfPublicHolidays = csv.reader(publicHolidays)
for currentRow in listOfPublicHolidays :
for currentEntry in currentRow :
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentEntry)
With the following
with open(fileName, accessMode) as publicHolidays :
listOfPublicHolidays = csv.reader(publicHolidays)
for currentRow in listOfPublicHolidays :
c.execute('INSERT INTO holidays VALUES (?, ?, ?, ?, ?)', currentRow)
However the cause of the error is still unclear to me.

Categories

Resources