Python SQLite Select from Database - python

My Database
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
# c.execute('''CREATE TABLE Karteikarten
# ([Frage] text, [Antwort] text)''')
F1 = input("Frage: ") A1 = input("Antwort: ")
c.execute('INSERT INTO Karteikarten Values ( ?, ?)', (F1, A1,))
# c.execute('SELECT * FROM Karteikarten')
# print(c.fetchall())
conn.commit()
conn.close()
Now to my question. How can I take the selected input from the database and print it out? I want to compare it with an input from a user later.
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
print(DBF1)
conn.commit()
conn.close()

If all you want to do is fetch output from the database, then you'd use
foo = c.fetchone()
or
foo = c.fetchall()
to store the output from the database into a variable
You would then print(foo)
IE:
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
DBF1 = c.fetchone() # or c.fetchall()
print(DBF1)
conn.commit()
conn.close()

Just fetch your result before the print statement.
Change this:
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
to this:
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1').fetchall()
and print(DBF1) will give you the desired output as a list of tuples

Related

sqlite3/tkinter: how do I remove treeview row using rowid from database

from tkinter import *
import sqlite3
app = Tk()
app.geometry('1000x600')
def remove_one():
x = my_tree.selection()[0]
my_tree.delete(x)
conn = sqlite3.connect('CustomerRecords.db')
c = conn.cursor()
rowid = c.lastrowid
c.execute("DELETE from customers WHERE rowid = ", (rowid))
conn.commit()
conn.close()
remove_one_button = Button(button_frame, text = 'Remove Record', command= remove_one)
remove_one_button.grid(row =0, column=2, padx = 10, pady = 10)
app.mainloop()
output:
sqlite3.OperationalError: incomplete input
I want to be able to delete a row from sqlite3 database using the row id that is naturally assigned to each row
The DELETE SQL statement is obviously incomplete, it should be:
c.execute("DELETE from customers WHERE rowid = ?", (rowid,))
How to get the rowid? If you insert those records into my_tree like below:
conn = sqlite3.connect('CustomerRecords.db')
c = conn.cursor()
c.execute('SELECT rowid, * FROM customers')
for row in c:
# use `iid` option to store the rowid
my_tree.insert('', 'end', iid=row[0], values=row[1:])
conn.close()
Then you can use my_tree.selection()[0] (you already did it in remove_one()) to get the rowid of the selected row.
Below is the modified remove_one():
def remove_one():
selected = my_tree.selection()
if selected:
rowid = selected[0]
my_tree.delete(rowid)
conn = sqlite3.connect('CustomerRecords.db')
c = conn.cursor()
c.execute("DELETE from customers WHERE rowid = ?", (rowid,))
conn.commit()
conn.close()
else:
print("No record selected")

sql python The value entered in the table is set first, the second is null

i create table
def sql_table_strategy():
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS strategy"
"(stra TEXT NOT NULL,"
"probability TEXT NOT NULL,"
" chat_id INTEGER UNIQUE)")
conn.commit()
cursor.close()
conn.close()
integraite strategy
def strategy_add(stra, ChatID):
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
val = (stra, ChatID)
sql = "INSERT OR IGNORE INTO strategy (stra,chat_id) VALUES (?,?)"
cursor.execute(sql, val)
conn.commit()
cursor.close()
conn.close()
add probability
def pr_add(probability, ChatID):
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
val = (probability,ChatID)
sql = "INSERT OR IGNORE INTO strategy (probability,chat_id) VALUES (?,?)"
cursor.execute(sql, val)
conn.close()
conn.close()
when I add the first strategy and then I add probability but in Columns probability is null
A solution for your problem.
def pr_add(probability, ChatID):
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
val = (probability,ChatID)
sql = "UPDATE strategy SET probability = ? WHERE chat_id = ?" --Change is here
cursor.execute(sql, val)
conn.close()
conn.close()

sqlite3.OperationalError: no such table: store

I'm learning sqlite3 with python, but I've been facing this error: "sqlite3.OperationalError: no such table: store". How do I get around this?
import sqlite3
def create_table(): #function to create the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(item, quantity, price ): #function to insert into the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("INSERT INTO store VALUES(?,?,?)", (item, quantity, price))
conn.commit()
conn.close()
insert("biscuits",500,20000)
def view():
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
return rows
conn.close()
print(view())
You forgot to call the create_table method before calling insert. As you haven't called the the create_table method the insert method tries to insert a record to a non existing table.
The solution is simply to call the create_table method before insert as follows:
create_table() # Add this line before the insert
insert("biscuits", 500, 20000)

Convert SQLITE 'NoneType in a int python

I'm trying to "SELECT" a value from Db and add this value to another variable, but when I execute this I get this error "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' "
id = input("Digite o id do cartão: ")
cash = int(input("Digite o o valor a ser creditado: "))
dia = 3
sql = 'SELECT saldo FROM carteira where idcartao = ?'
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
row = c.fetchone()
soma = (row) + (cash)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (soma, id))
connection.commit()
selectbanco()
THIS IS MY COMPLETE CODE
import sqlite3
connection = sqlite3.connect('clientes.db')
c = connection.cursor()
#criação de tabela
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS carteira (idcartao REAL, saldo REAL, data text)')
create_table()
#variaveis
id = input("Digite o id do cartão: ")
cash = int(input("Digite o o valor a ser creditado: "))
dia = 3
sql = 'SELECT saldo FROM carteira where idcartao = ?'
#SELECT E RETORNAR VALOR
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
row = c.fetchone()
##soma = (row + cash)
##print(soma)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (cash, id))
connection.commit()
selectbanco()
#leitura do banco
def read_data(wordUsed):
for row in c.execute(sql, (wordUsed,)):
print (row)
read_data(id)
connection.close()
You've got two issues here.
The first is that you exhaust your generator by calling row = c.fetchone() twice, without re-executing the query. You can only iterate through your cursor once for each query result; after that, you will need to re-run the query to "refresh" the data and be able to iterate again.
Second, fetchone() will actually return None if you get no matches. This is in contrast to fetchall() that will instead return an empty list ([]) in the case of no matches.
This quick example should illustrate this behaviour:
import sqlite3
# Create a fake database
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS some_table(
something TEXT
)""")
c.execute(""" INSERT INTO some_table VALUES('hello') """)
c.execute("SELECT * FROM some_table")
# We get a match and this will print '(hello,)'
data = c.fetchone()
print(data)
data = c.fetchone()
# If we don't execute the query again but try to use the exhausted generator
# then we'll also get None
print(data)
c.execute("SELECT * FROM some_table WHERE something = 'bye'")
# This will print 'None' because fetchone() didn't get a result
data = c.fetchone()
print(data)
c.execute("SELECT * FROM some_table WHERE something = 'bye'")
# This will print an empty list because fetchall() didn't get a result
data = c.fetchall()
print(data)
c.close()
conn.close()
Even though None and [] are different, they are still falsey so, in the context of your question, you can still convert either response to an integer:
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""create table if not exists some_table(
something TEXT
)""")
c.execute(""" INSERT INTO some_table VALUES('hello') """)
# Get back None or an integer
c.execute(""" SELECT * FROM some_table WHERE something = ?""", ('bye', ))
data = c.fetchone() or 1 # This is where you return an integer instead of None
print(data)
c.close()
conn.close()
I've picked an integer value of 1, maybe you want 0, I'm not sure. The thing to note, though, is that there's two avenues for you to get None or falsey data here, and you're treating them both the same, which isn't great for clarity of code.
You are fetching row twice. You need to remove the second fetch to receive the row.
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
soma = (row) + (cash)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (soma, id))
connection.commit()
selectbanco()
The variable gets overwritten because you do not specify a command to execute before fetching (the second time), hence the NoneType.

How do I make a return statement from this loop

I have this code and i need to get the lastrowid as a return statement. How can i fix it
def main():
while True:
#code here
for item in name2:#break
conn = sqlite3.connect("foods.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO INPUT33 (NAME) VALUES (?);", (name2,))
cursor.execute("select MAX(rowid) from [input33];")
conn.commit()
conn.close()
for rowid in cursor:break
for elem in rowid:
return rowid#this is not working
print(m)
You closed the database, so any cursor no longer has access to the data. Retrieve the data before closing. I am assuming here that you have a reason to re-open the database in a loop here.
def main():
while True:
for item in name2:
conn = sqlite3.connect("foods.db")
cursor = conn.cursor()
with conn:
cursor.execute("INSERT INTO INPUT33 (NAME) VALUES (?);", (name2,))
cursor.execute("select MAX(rowid) from [input33];")
rowid = cursor.fetchone()[0]
conn.close()
return rowid

Categories

Resources