Python sqlite3 error about number of bindings supplied - python

I'm sure this has been asked, and answered before, but either I'm stupid or then none of the answers work for me. Maybe I just don't understand it. However, here's the problem; I got this class:
import sqlite3
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def saveToDatabase(self):
connection = sqlite3.connect("users.db")
cur = connection.cursor()
cur.execute("DROP TABLE IF EXISTS users")
cur.execute("CREATE TABLE users (name TEXT PRIMARY KEY, age INTEGER)")
cur.execute("INSERT OR REPLACE INTO users VALUES (?,?)", (self.name, self.age))
connection.commit()
connection.close()
#staticmethod
def printUserFromDatabase(name):
connection = sqlite3.connect("users.db")
cur = connection.cursor()
cur.execute("SELECT * FROM users WHERE name=?", name)
print(cur.fetchone())
connection.close()
And it works, database gets created, and I can add users to it, but when ever I try to print an user from database, this happens:
>>> tom = User("Tom", 24)
>>> tom.saveToDatabase()
>>> User.printUserFromDatabase("Tom")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
User.printUserFromDatabase("Tom")
File "C:\Users\Markus\Desktop\foo\foo.py", line 25, in printUserFromDatabase
cur.execute("SELECT * FROM users WHERE name=?", name)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.
>>>

since name is iterable it tries to unpack it ... put it in a tuple with just itself to fix
cur.execute("SELECT * FROM users WHERE name=?", (name,))

Related

Reset row_factory attribute of an Python sqlite3 object

How can I reset the "row_factory" attribute of an sqlite3 connection object after setting it to "sqlite3.Row"? For instance:
import sqlite3
con = sqlite3.connect("db.dat", isolation_level=None)
con.row_factory = sqlite3.Row
cur = con.execute("insert into test1 (name, last) values (?, ?)", ("John","doe"))
cur = con.execute("insert into test1 (name, last) values (?, ?)", ("Liz","doe"))
cur.execute("select * from test1")
cur.fetchone() # gets {'name':'john', 'last':'doe'}
# Now I want to get a tuple when calling fetchone
con.row_factory = None
cur.fetchone() #Throw error
delattrib(con, "row_factory") # causes segmentation fault on Windows
I can't find an answer anywhere and the only solution (other than casting the dictionary) is to reopen the db connection. I read the documentation for the sqlite3 module, but it doesn't mention anything to reset the attribute back to its default state.
Thank you

Can I select just one specific element in a sql query(select statement)?

I am trying to create a command line tool that generates a random string(password) of a given length, stores it in a sql db, and can be queried by name. The password generation and storing of it's output by a given name works beautifully, but trying to select only the password element is giving me trouble. I was able to select all from the table but that returns the name and the password. I only want the password returned. I thought about just splicing the output or even using the linux cut command, but I'd rather just get it from the select statement. Is this possible? My current SELECT statement returns: operation parameter must be a str. When I try it without the call to (name) at the end of the SELECT statement like this: query_password = """SELECT * FROM password_table WHERE name = ?"""
I get this error:
File "passbox.py", line 44, in <module>
query_pswd_by_name(name)
File "passbox.py", line 39, in query_pswd_by_name
c.execute(query_password)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.
BTW I'm sure my query_pswd_by_name function is all wrong, I've been experimenting. When I just create a connection and SELECT statement outside of a function it does return the name and password.
Also note that I've disguised my database file's name with asterisks for the purpose of this post. I am using an actual working db file in practice.
Here is all the code I've written so far:
import secrets
import string
import sqlite3
#CREATE PASSWORD OF GIVEN LENGTH
def get_pass(length):
return "".join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) for x in range(length))
length = int(input("Enter the length of password: "))
password= get_pass(length)
print(password)
name = str(input("Enter name for password: "))
#CREATE DATABASE CONNECTION
conn = sqlite3.connect("****.db")
#CREATE CURSOR OBJECT
c = conn.cursor()
#CREATE TABLE IN DISK FILE BASED DATABASE
c.execute("""CREATE TABLE IF NOT EXISTS password_table (
name TEXT,
pswd TEXT
)""")
c.execute("INSERT INTO password_table (name, pswd) VALUES (?, ?)", (name, password))
#COMMIT CHANGES
conn.commit()
conn.close()
def query_pswd_by_name(name):
conn = sqlite3.connect('****.db')
c = conn.cursor()
query_password = """SELECT * FROM password_table WHERE name = ?""", (name)
c.execute(query_password)
result = c.fetchall()
for row in result:
print(row[1])
conn.commit()
query_pswd_by_name(name)
#CLOSE CONNECTION
conn.close()```
You need to break up the argument to the execute call.
c.execute(*query_password)
Or
c.execute("""SELECT * FROM password_table WHERE name = ?""", (name))

sqlite3 database query in python

I tried performing a search query from the backend of an app I'm working and I got the response below:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
ValueError: parameters are of unsupported type
I have the code below:
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan Number TEXT, Tracing Number TEXT, Submitted By TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
rows = cur.fetchall()
conn.close()
return rows
self.NmRqst.text is the QLineEdit that accepts the user input for database query...
Feel free to correct the question as you deem fit!
I have edited the lines of code,
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan_Number TEXT, Tracing_Number TEXT, Submitted_by TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
rows = cur.fetchall()
conn.close()
return rows
...and I got the following error:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 64 supplied.

Python 3 + SQLite check

Hello
I have a question about SQLite functions, maybe.
So, question:
How to check if name I set in Python is in certain column?
Example:
name = 'John'
Table name = my_table
Column name = users
Code details:
C = conn.cursor()
Please
Use parameter in the query as required. See the attached example for better understanding.
Sample SQLite code for searching value in tables
import sqlite3 as sqlite
import sys
conn = sqlite.connect("test.db")
def insert_single_row(name, age):
try:
age = str(age)
with conn:
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS USER_TABLE(NAME TEXT, AGE INTEGER);")
cursor.execute("INSERT INTO USER_TABLE(NAME, AGE) VALUES ('"+name+"',"+age+")")
return cursor.lastrowid
except:
raise ValueError('Error occurred in insert_single_row(name, age)')
def get_parameterized_row(name):
try:
with conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM USER_TABLE WHERE NAME = :NAME",
{"NAME":name})
conn.commit()
return cursor.fetchall()
except:
raise ValueError('Error occurred in get_parameterized_row(name)')
if __name__ == '__main__':
try:
return_id = insert_single_row("Shovon", 24)
return_id = insert_single_row("Shovon", 23)
return_id = insert_single_row("Sho", 24)
all_row = get_parameterized_row("Shovon")
for row in all_row:
print(row)
except Exception as e:
print(str(e))
Output:
('Shovon', 24)
('Shovon', 23)
Here I have created a table called USER_TABLE with two attributes: NAME and AGE. Then I inserted several values in the table and searched for a specific NAME. Hope it gives a way to start using SQLite in the project.

SQLITE3 DB data transfer from one field to another in the same table and same row

I'm trying to move data in the same row from one field to another.
This is my code, but it doesn't work with the update statement:
def update_ondemanddrama(Name):
with sqlite3.connect("sky_ondemand.db") as db:
cursor = db.cursor()
sql = "update TVshowsDrama set SecLastEp=LastEp where Name=?"
cursor.execute(sql, Name)
db.commit()
works
def insert_ondemanddrama(values):
with sqlite3.connect("sky_ondemand.db") as db:
cursor = db.cursor()
sql = "update TVshowsDrama set Name=?, LastEp=? where Name=?"
cursor.execute(sql,values)
db.commit()
def insert_ondemanddoc(values):
with sqlite3.connect("sky_ondemand.db") as db:
cursor = db.cursor()
sql = "update TVshowsDoc set Name=?, LastEp=? where Name=?"
cursor.execute(sql,values)
db.commit()
Type = int(input("Doc (1) or Drama (2)"))
Name = input("Enter name of Show")
LastEp = input("Enter Last episode aired (ex. s1e4)")
if Type == 1:
if __name__== "__main__":
show = (Name, LastEp, Name)
insert_ondemanddoc(show)
elif Type == 2:
if __name__== "__main__":
show = (Name, LastEp, Name)
update_ondemanddrama(Name)
insert_ondemanddrama(show)
elif Type >=3:
print ("Incorrect entry")
The error I get running this in python is:
Traceback (most recent call last): File "C:\Users\ict\Downloads\skyondemandv1.py", line 65, in <module>
update_ondemanddrama(Name) File "C:\Users\ict\Downloads\skyondemandv1.py", line 34, in
update_ondemanddrama cursor.execute(sql, Name) sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses 1, and there are 5 supplied.
cursor.execute expects an iterable. When you give it a string, execute perceives it as a 5 item iterable (5 characters).
Change the execute line to
cursor.execute(sql, (Name,))

Categories

Resources