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,))
Related
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.
I want to insert variable values into db2 table using Python code
id = input("table id: ")
tabname = input("Enter Table name: ")
descr = input("Enter description : ")
inser_sql = "INSERT INTO schema.table VALUES (?, ?, ?)",(id, tabname, descr)
stmt = ibm_db.prepare(conn, inser_sql)
ibm_db.execute(stmt)
this code gives me error:
stmt = ibm_db.prepare(conn, inser_sql)
Exception: statement must be a string or unicode
Assuming that your table is defined like this:
"create table myschema.mytable(id int, tabname varchar(10), description varchar(10))"
I understand your intention is to insert a specific row into it with a prepared statement and parameter markers.
Skipping the input part:
In [14]: id = 1
In [15]: tabname = 'TAB'
In [16]: descr = 'my desc'
you just need to prepare the statement first, bind the parameters later and then execute:
insert_sql = "INSERT INTO myschema.mytable VALUES (?, ?, ?)"
prep_stmt = ibm_db.prepare(conn, insert_sql)
ibm_db.bind_param(prep_stmt, 1, id)
ibm_db.bind_param(prep_stmt, 2, tabname)
ibm_db.bind_param(prep_stmt, 3, descr)
ibm_db.execute(prep_stmt)
The exact answer will depend on the specific DB2 library you're using, but the variable holding your query should just be a plain string.
You will probably need to pass parameters to it when you execute the statement:
inser_sql = "INSERT INTO schema.table VALUES (?, ?, ?)"
stmt = ibm_db.prepare(conn, inser_sql)
ibm_db.execute(stmt, (id, tabname, descr))
# ^^^^^^^^^^^^^^^^^^^^
I am getting the error 'sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied.' The below code should be making a database and creating a table with the the titles listed below. Then take values from a csv. file and add it under the allotted headings. Any help would be would be appreciated!
import const
import sqlite3
SEP = ','
DATA_FILENAME = 'pokemon.csv'
con = sqlite3.connect('poki.db')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS poki')
cur.execute( ' CREATE TABLE poki( pokemon TEXT, species_id INTEGER,'
' height REAL, weight REAL)' )
values = ('INSERT INTO poki VALUES (?, ?, ?, ?)')
for line in DATA_FILENAME:
list_of_values = line.strip().split(SEP)
cur.execute(values, list_of_values)
cur.close()
con.commit()
con.close()
having trouble with these two functions
was wondering if people could tell me where I am going wrong
this is a separate function as part of a spider that searches through a website of house prices
def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE houses (id, address, postcode, bedrooms) VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id, date, sale_price) VALUES'
'(%d %s %s)' %(id, sale_price, str(date)))
d.commit()
d.close()
here is the error raised:
Traceback (most recent call last):
File "/Users/saminahbab/Documents/House_Prices/final_spider.py", line 186, in <module>
final_function(link_set=areas,id_counter=40)
File "/Users/s/Documents/House_Prices/final_spider.py", line 158, in final_function
page_stripper(link=(root+page), id_counter=id_counter)
File "/Users/s/Documents/House_Prices/final_spider.py", line 79, in page_stripper
save_house_to_db(id=float(id_counter), address=address, postcode=postcode, bedrooms=bedrooms)
File "/Users/s/Documents/House_Prices/final_spider.py", line 25, in save_house_to_db
d.execute('INSERT INTO TABLE houses VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
sqlite3.OperationalError: near "TABLE": syntax error
and for reference here is the execute for the databse
# conn = sqlite3.connect('houses_in_london.db')
# database = conn.cursor()
# database.execute('CREATE TABLE houses (id INTEGER PRIMARY KEY, address TEXT,'
# 'postcode TEXT, bedrooms TEXT)')
#
# database.execute('CREATE TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id INTEGER '
# ' REFERENCES houses(id), date TEXT, sale_price INTEGER )')
as always, thank you for the support
You have many issues:
INSERT-clause has no TABLE keyword
You're trying to pass variables to an SQL query using string formatting; don't do it, ever – use placeholders, or face the consequences
Your VALUES-clause is missing commas between the value-expressions
The sqlite3 module uses "?" as a placeholder instead of percent formatters
"transaction_id NOT NULL AUTO_INCREMENT" is not a valid column name
"AUTO_INCREMENT" is not valid SQLite syntax and you probably meant for transaction_id to be INTEGER PRIMARY KEY – also AUTOINCREMENT should usually not be used
The below functions fix some of the errors, barring the DDL-corrections to the transactions table.
def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# Remove the TABLE "keyword"
d.execute('INSERT INTO houses (id, address, postcode, bedrooms) '
'VALUES (?, ?, ?, ?)', (id, address, postcode, bedrooms))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# This here expects that you've fixed the table definition as well
d.execute('INSERT INTO transactions (house_id, date, sale_price) '
'VALUES (?, ?, ?)', (id, sale_price, date))
d.commit()
d.close()
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.