How to turn an interger list to single value tuples - python

I wrote a code to delete some users from the database, but it said Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.
def delete_user(self, user_id):
stmt = "DELETE FROM user WHERE user_id = (?)"
args = user_id
try:
self.conn.executemany(stmt, (args,))
self.conn.commit()
except sqlite3.Error as e:
logging.error(str(e))
My part main code:
deleted_user = []
deleted_user.append(1384995383)
deleted_user.append(1667596031)
deleted_user.append(1332658866)
deleted_user.append(1295962235)
print(deleted_user)
db.delete_user(deleted_user)
I found this answer: sqlite3: Incorrect number of bindings supplied. The current statement uses 1, and there are 5 supplied
I try to use tuple(user_id) to convert it to a tuple, but the result was not I'm except
Origin deleted_user list:
[1384995383, 1667596031, 1332658866, 1295962235]
After tuple(user_id) result:
(1384995383, 1667596031, 1332658866, 1295962235)
What I Expectation:
[(1384995383,), (1667596031,), (1332658866,), (1295962235,)]
I tried searching, but I couldn't get the answers I wanted :(

def delete_user_ids(self, user_ids):
stmt = "DELETE FROM user WHERE user_id = (?)"
try:
self.conn.executemany(stmt, user_ids)
# ^^^^^^^^
user_ids = []
user_ids.append((1384995383,))
user_ids.append((1667596031,))
user_ids.append((1332658866,))
user_ids.append((1295962235,))
delete_user_ids(user_ids)

Try this:
deleted_user.append((1384995383,))

Related

How to update a SQL database based of a user input in python

I am trying to make a shopping cart code in python using sql, but when I try and update the shopping cart database table, it doesn't work and runs the except code, and I am not sure where the error is with the code, but it just prints "Added to cart successfully" so instead of printing "Updated cart successfully", so the second part of the code works, as it adds the item to the database, but when I try and put in the same item again, it doesn't do the first part of the code.
search_bar_2 = input("Enter what item you would like to look up >>> ")
#ask the user what item they are looking for specifically
try:
sql = "SELECT * FROM Items_in_stock WHERE item_name = ?"
#select everything from items_in_stock where the item_name has a placeholder that will be determined later.
cursor.execute(sql, (search_bar_2,))
#Executes the sql and adds the search_bar_2 as the value for the placeholder.
item = cursor.fetchone()
#gets one item from the database and saves it as item in python
print("id: ", item[0], "\nname of item: ", item[1], "\nquantity: ", item[2])
#prints each element of the tuple item seperatly with the corresponding text beforehand
add_to_cart = input("Would you like to add this item to your cart? (y/n) >>> ")
#asks the user if they want to save the item displayed to them to their cart. this response will either need to be a y for yes or n for no.
if add_to_cart == 'y':
# if the user answered yes
try:
sql3 = ('SELECT item_quantity FROM Shopping_cart WHERE item_name = ?')
cursor.execute(sql3, (search_bar_2,))
quantity_selector = cursor.fetchone()
quantity_selector += 1
cursor.execute('UPDATE Shopping_cart SET item_quantity = ? WHERE item_name = ?', (quantity_selector, search_bar_2))
connection.commit()
print("Updated cart successfully")
except:
add_cart = "INSERT INTO Shopping_cart(item_ID, item_name, item_quantity) VALUES (?, ?, ?)"
#adds the items to the cart, to do so, a placeholder was given to each element of shopping_cart that will need to be filled with the information of the items.
item_values = (item[0], item[1], 1)
cursor.execute(add_cart, item_values)
connection.commit()
print("Added to cart successfully")
except:
print("There is an error with the search item.")
the bit that doesn't work is the bit after "If add_to_cart == 'y'"
Thanks in advance for the help.
Quick Solution: quantity_selector is not what you think it is.
quantity_selector = cursor.fetchone() #Probably returns
-> (1,)
quantity_selector+=1 #FAILS going to your except clause
Consider:
quantity_selector = cursor.fetchone()[0] #Fails if no result so goes to except as expected
-> 1
quantity_selector+=1
-> 2
On a side note, it really isn't a good idea to use a bare try/except all the time without specifying clearly what you are trying to do or what errors you are suppressing or use as logic. You may accidentally hide errors that would have popped up.
Addendum: Since the value is a string the simplest correction would be
quantity_selector = int(cursor.fetchone()[0]) #Fails if no result so goes to except as expected. Now casts the value as integer so that the addition will work.
-> 1
quantity_selector+=1
-> 2
ALthough the above is the simplest fix, it probably means you should probably change the schema of your sql table to keep it as integers so you don't get weird behaviours such as letters in a column that should be integers.

Database in python - index issue

for page in range(1, pages + 1):
def append_organizator(organizator, organizatorzy=[]):
organizatorzy.append(organizator)
for i in organizatorzy:
try:
query = "INSERT INTO stypendia (organizator) values(%s)"
values = []
values.append(organizatorzy.pop())
cursor.execute(query, values)
conn.commit()
except:
pass
def append_type(rodzaj, rodzaje=[]):
rodzaje.append(rodzaj)
for i in rodzaje:
try:
query = "INSERT INTO stypendia (rodzaj) values(%s)"
values = []
values.append(rodzaje.pop())
cursor.execute(query, values)
conn.commit()
except:
pass
Those are 2 functions that are inserting the data scrapped from website into the database
The program is iterating through all available pages on site. The data that's scrapped is inserted to database.
As you can see on screenshot, the title is inserted 7 times(the amount of pages), then the organizator again 7 times etc...
How can i solve this problem and have everything at same indexesdatabase ss
You need to combine the insert operations - each insert will create a new row. You should also just use the parameters without the array, they really aren't needed.
This example only handles two parameters (same as your code above). Add additional parameters as needed and adjust the insert statement
# The organization of this loop assumes the order of returned data is
# consistent: each "rodzaj" is at the same index as its "organizator"
# (as the original code assumes)
organizator = doc.find_all(class_='organizator-title')
rodzaj = doc.find_all('div', class_='fleft', string="Rodzaj:")
for i in range(min(len(organizator), len(rodzaj))):
o = organizator[i].text.strip().replace('\\n', '').replace('\\r', '')
r = rodzaji].find_next().text.strip().replace('\\n', '').replace('\\r', '')
append(o, r)
def append(organizator: str, rodzaj: str):
try:
query = "INSERT INTO stypendia (organizator, rodzaj) values(%s, %s)"
values = (organizator, rodzaj)
cursor.execute(query, values)
conn.commit()
except:
pass

Python SQLite3 issue searching table

I have a Python function that is supposed to check if a value is present in my SQLite table. I have a table named Users and it stores the value userid which is a random string of integers and letters. For example, a userid would look like this f75fsf3dbg9g. In def chk(): the user inputs their uid then the uid_chk(): function is called to check if the uid value equals one of the userid being stored in the table.
My issue is in the cur.execute(query,tagValue) line in the uid_chk() function. It throws the Error: sqlite3.programmingError: Incorrect number of bindings supplied. The current statement uses 1
Nothing is being returned from the function uid_chk() just prints out None
For reference when the table Users is printed out it looks like this: [('hk12lkj14vh',),('bn465i32',),('d8j4k0fl',),('k4i9b3k0s2',),('rk2nk50sp26',),('rk3ji9al23',),]
import RPi.GPIO as GPIO
import sqlite3 as sql
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()
def chk():
print("Scan tag")
try:
uid_tag = reader.read()
#If the user has inputed value (uid)
if uid_tag :
#Var for inputed userid
tagValue = uid_tag[1]
print(tagValue)
uid_chk(tagValue)
return tagValue
GPIO.cleanup()
except ValueError:
print('Something went wrong')
def uid_chk(tagValue):
Database = sql.connect('test.db')
# cursor
cur = Database.cursor()
# Check if the tagValue maches a value in the userid column of sqlite DB
query = 'SELECT userid FROM Users WHERE userid = ?'
cur.execute(query, tagValue)
row_returned = cur.fetchone()
print(row_returned)
if row_returned == tagValue:
print('User Verified')
else:
print('Something is Wrong')
Database.close()
chk()

Returning department courses in databases

I think I have the right idea to do this function but I'm not sure why I get
this error when I test it. Can anyone please help me fix this?
cur.execute(q)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
current statement uses 1, and there are 0 supplied.
Current Attempt
def find_dept_courses(db, dept):
'''Return the courses from the given department. Use the "LIKE"
clause in your SQL query for the course name.'''
return run_query(db, '''SELECT DISTINCT Course FROM Courses WHERE
Course LIKE (? + 'dept%')''')
Desired output
find_dept_courses('exams.db', 'BIO')
# [('BIOA01H3F',), ('BIOA11H3F',), ('BIOB10H3F',), ('BIOB33H3F',),
# ('BIOB34H3F',), ('BIOB50H3F',), ('BIOC12H3F',), ('BIOC15H3F',),
# ('BIOC19H3F',), ('BIOC32H3F',), ('BIOC37H3F',), ('BIOC50H3F',),
# ('BIOC58H3F',), ('BIOC59H3F',), ('BIOC61H3F',), ('BIOC63H3F',),
# ('BIOD21H3F',), ('BIOD22H3F',), ('BIOD23H3F',), ('BIOD26H3F',),
# ('BIOD33H3F',), ('BIOD48H3F',), ('BIOD65H3F',)]
query function:
def run_query(db, q, args=None):
"""(str, str, tuple) -> list of tuple
Return the results of running query q with arguments args on
database db."""
conn = sqlite3.connect(db)
cur = conn.cursor()
# execute the query with the given args passed
# if args is None, we have only a query
if args is None:
cur.execute(q)
else:
cur.execute(q, args)
results = cur.fetchall()
cur.close()
conn.close()
return results
While using .execute you need to pass the argument as a list or tuple, here is the sample
# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))
Currently, you are using a placeholder but do not pass any parameters. Secondly, you are concatenating placeholder ? with a data value in LIKE expression.
Simply separate query statement and data value and leave ? by itself:
def find_dept_courses(db, dept):
sql = '''SELECT DISTINCT Course FROM Courses WHERE Course LIKE ?'''
return run_query(db, sql, args=(dept+'%',))
Remove the ? and resolve your sql syntax so dept is treated as a variable e.g. sql should evaluate to
SELECT DISTINCT Course FROM Courses WHERE
Course LIKE 'mydept%'
Note you may be susceptible to sql injection with this method and dept is from user input

MySQLdb - Check if row exists Python

I am trying to check if a row exist with the same Name my database with python and can't quite get it here is what I am trying: (I know the connection is wokring)
try:
cursor.execute("SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name"), (item_name)
catch:
print "it does not exist"
Can someone help me out here
Thanks
First of all you have a wrong syntax in your code. Python doesn't have a try...catch block. It has try...except block which is used like this:
try:
# something here
except:
# something here
MySQL does not return an error when you use SELECT command. However there are two different ways you can find out if it returned something or not.
PYTHON 2.7
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print "number of affected rows: {}".format(row_count)
if row_count == 0:
print "It Does Not Exist"
PYTHON 3+
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print ("number of affected rows: {}".format(row_count))
if row_count == 0:
print ("It Does Not Exist")
Another way to do this would be to fetch the statement and check if it is empty:
# execute statement same as above
msg = cursor.fetchone()
# check if it is empty and print error
if not msg:
print 'It does not exist'
This is my first answer, so I don't know how to style the code in the answer properly, it also seems messy because of that. Sorry for that.
Also i use Python 3 and pymysql, so there may be some syntax error but I have tried to write the code according to python 2.7 from what I could remember about it.
EDIT (5/1/2020)
Thanks to #Arishta for pointing out that the first method will require you to fetch all rows before using row_count. i.e adding cursor.fetchall() before the row_count = cursor.rowcount
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# Add THIS LINE
results = cursor.fetchall()
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print("number of affected rows: {}".format(row_count))
if row_count == 0:
print("It Does Not Exist")
Use the cursor.fetchone() if you only care if the record exists or not.
If you want to check for empty results, try if cur.description is None:
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT
As well as:
exist = cursor.fetchone()
if exist is None:
... # does not exist
else:
... # exists
If you are running a statement that would never return a result set
(such as INSERT without RETURNING, or SELECT ... INTO), then you
do not need to call .fetchall(); there won't be a result set for
such statements. Calling .execute() is enough to run the statement.
cursor.execute("SELECT * FROM userinfo WHERE User_Name=%s",(userid,))
data="error" #initially just assign the value
for i in cursor:
data=i #if cursor has no data then loop will not run and value of data will be 'error'
if data=="error":
print("User Does not exist")
else:
print("User exist")

Categories