sqlite3.OperationalError: no such table: store - python

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)

Related

SQLITE and PYQT5 stopping to respond on sql execution

I was building a todo app and used the sql-lite python database for it. I added the clear command and all was going well until I found out when I cleared the database and then tried to view it, my pyqt application just stopped responding.
The database code:
def db(self):
title = self.textEdit.toPlainText()
desc = self.textEdit_2.toPlainText()
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS task
(title text, desc text)
""")
cur.execute("INSERT INTO task VALUES(?,?)", (title, desc))
conn.commit()
cur.close()
conn.close()
the code to view the database [within qt application]
def showdb(self):
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
str = ''
str2 = ''
self.tableWidget.setRowCount(50)
tableindex = 0
amount = len(cur.execute('SELECT * FROM task').fetchall())
if amount > 0:
for x in cur.execute('SELECT * FROM task'):
str = ''.join(x[0])
str2 = ''.join(x[1])
self.tableWidget.setItem(tableindex, 0, QtWidgets.QTableWidgetItem(str))
self.tableWidget.setItem(tableindex, 1, QtWidgets.QTableWidgetItem(str2))
tableindex += 1
else:
pass
the code to clear the database [it stops to respond after i click it]
def delete(self):
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute('DROP TABLE task')
conn.commit()
The problem is in your delete function, after dropping the database you are not creating it again. This line of code should fix the error.
def delete(self):
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute('DROP TABLE task')
cur.execute("""CREATE TABLE IF NOT EXISTS task
(title text, desc text);
""")
conn.commit()

Python SQLite Select from Database

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

Not getting results from database - sqlite 3

I'm trying to insert a large list of English words into a database, and get the results back. However, when I query the database, it is returning nothing. I have omitted the input of the text file into the database for this example, and have only inserted a single string. However this is not showing up in the query either. Here is my code:
import sqlite3
def get_database_connection():
return sqlite3.connect("myDatabase.db")
def commit():
connection = get_database_connection()
connection.commit()
connection.close()
def table_exists(table):
cursor = get_cursor()
cursor.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='{0}' '''.format(table))
my_bool = cursor.fetchone()[0]
return my_bool
def get_cursor():
connection = sqlite3.connect("myDatabase.db")
cursor = connection.cursor()
return cursor
def create_table(table):
if table_exists(table):
return
cursor = get_cursor()
cursor.execute("""CREATE TABLE {0}(
word text
)""".format(table))
def insert_english_words():
#english_words = "english.txt"
#words = process_words(english_words)
table = "english"
create_table(table)
cursor = get_cursor()
cursor.execute("INSERT INTO english VALUES ('HELLO')")
#for word in words:
#cursor.execute("INSERT INTO english VALUES ('{0}')".format(word))
commit()
def get_data():
cursor = get_cursor()
cursor.execute("SELECT * FROM english")
rows = cursor.fetchall()
for row in rows:
print(row)
def run():
get_database_connection()
insert_english_words()
get_data()
print("Done")
run()
You have to commit after creation of table.
Maintain one single connection object across your script lifecycle. You are creating a new connection every single time.

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()

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