Not getting results from database - sqlite 3 - python

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.

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

View Function used to work now it does not

import sqlite3
def create_table():
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS shop (item TEXT, quantity INTEGER, price REAL)') #you write the SQL code in between brackets
connection.commit()
connection.close()
create_table()
def insert(item,quantity,price):
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute("INSERT INTO shop VALUES (?,?,?)", (item,quantity,price)) # inserting data
connection.commit()
connection.close()
insert('Wine Glass', 10, 5)
insert('Coffe Cup', 5, 2)
insert('Plate', 20, 10)
def view():
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute('SELECT ALL FROM shop ')
rows = cursor.fetchall()
connection.close()
return rows
def delete_item(item):
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute("DELETE * FROM shop WHERE item = ?", (item,)) # inserting data
connection.commit()
connection.close()
print(view())
delete_item('Wine Glass')
print(view())
Error Message:
cursor.execute('SELECT ALL FROM shop ')
sqlite3.OperationalError: near "FROM": syntax error
It used to work and then I added the delete function and now it gives me this syntax error, I didn't even make any changes on that function. The code is based on a Udemy tutorial, and with the same changes applied on the video I got this error message but the tutor did not. As you can guess I am pretty new to this stuff and I cant decipher the error message, or at least if it means any more than the obvious. So yeah thanks in advance
SELECT ALL should be SELECT ALL * or just SELECT * to select all columns in all rows. See the syntax here.
DELETE * FROM shop should be DELETE FROM shop. DELETE deletes whole rows, it doesn't need a list of columns. See the syntax here.

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)

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

MySQL did not give an error, but none of the rows got filled

I tried to fill a table in a database using MySQLdb. It did not give any errors, and once gave the warning
main.py:23: Warning: Data truncated for column 'other_id' at row 1
cur.execute("INSERT INTO map VALUES(%s,%s)",(str(info[0]).replace('\n',''), str(info[2].replace('\n','').replace("'",""))))
so I thought it was working fine. However, when it was finished and I did a row count it turned out that nothing was added. Why was the data not added to the database? The code is below
def fillDatabase():
db = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="",
db="uniprot_map")
cur = db.cursor()
conversion_file = open('idmapping.dat')
for line in conversion_file:
info = line.split('\t')
cur.execute("INSERT INTO map VALUES(%s,%s)",(str(info[0]).replace('\n',''), str(info[2].replace('\n','').replace("'",""))))
def test():
db = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="",
db="uniprot_map")
cur = db.cursor()
cur.execute("SELECT COUNT(*) FROM map")
rows = cur.fetchall()
for row in rows:
print row
def main():
fillDatabase()
test()
You need to do a db.commit() after adding all of the entries. Even if the update is not transactional, the DBAPI imposes an implicit transaction on every change.

Categories

Resources