I created a basic database in python with sqlite3 which takes in 3 values and stores them. Now where the problem lies is that when I created a function that is supposed to output the values, no syntax errors were displayed on terminal and none of my values were printed. Im guessing this is a minor error but I am not able to spot it.
The code is given below:
import sqlite3
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity
INTEGER, price FLOAT)")
conn.commit()
conn.close()
def insert(item, quantity, price):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO store VALUES ('?, ?, ?')", (item, quantity,
price))
conn.commit()
conn.close()
insert("Mug", 8, 6)
def view():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
print(view())
Again no error messages were displayed but my values are not displayed.
I have tried it. it seems the single quotes are not needed in the insert. See modified below:
import sqlite3
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price FLOAT)")
conn.commit()
conn.close()
def insert(item, quantity, price):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO store VALUES (?,?,?)", (item, quantity, price))
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
create_table()
insert("Mug", 1, 5)
print(view())
Related
I wanna make a temporary database but I don't know I going in the right way or not
I get the error no such table: list but I don't know why python raise that error
this is my code:
def connect():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS list (id INTEGER PRIMARY KEY , namee VARCHAR , number INTEGER ,"
" price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, number, price):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"INSERT INTO list VALUES (NULL ,?,?,?,?,?)", (name, number, price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"SELECT * FROM list"
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("DELETE FROM list WHERE id=?", (id,))
conn.commit()
conn.close()
connect()
and this is my error:
Traceback (most recent call last):
File "D:\python\WindowsProject\app\user\memory.py", line 42, in <module>
print(insert('pizza',2,6))
File "D:\python\WindowsProject\app\user\memory.py", line 17, in insert
cur.execute(
sqlite3.OperationalError: no such table: list
sqlite3.connect(":memory:") creates an in-memory database that only exists as long as the connection is in use.
The problem is that you're closing the database connection in each function. As soon as you close it, the in-memory database vanishes. INSERT fails because the table no longer exists.
You'll need to preserve (or pass) the conn and cur objects so that you can use them between functions.
I working on a project and I want to use one database in two python file
but, when I run every project they created database for self
if you know please tell me how I can use that
import sqlite3
def connect():
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS salary (id INTEGER PRIMARY KEY , name text, age INTEGER , price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, age, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"INSERT INTO salary VALUES (NULL ,?,?,?)", (name ,age ,price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"SELECT * FROM salary"
)
rows = cur.fetchall()
conn.close()
return rows
def search(name="", age="", price=""):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"SELECT * FROM salary WHERE name = ? OR age = ? OR price = ?", (name, age, price)
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute("DELETE FROM salary WHERE id=?", (id,))
conn.commit()
conn.close()
def update(id, name, age, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"UPDATE salary SET name = ?, age = ?, price = ? WHERE id = ?", (name, age, price, id)
)
conn.commit()
conn.close()
def update_pay_money(name, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"UPDATE salary SET price = ? WHERE name = ?", (price, name)
)
conn.commit()
conn.close()
connect()
enter image description here
Giving exact path like /path/to/waiters.db while connecting to your database should solve your problem?
This line should be changed while connecting to database.
conn = sqlite3.connect("/path/to/waiters.db")
as Other mentioned for using a sqllite3 db in multiple files you can use their absolute or relative path, for example if you have 'DBs' & 'section-1' & 'section-2' directories and your python file are in section directories you can access the database file in each section by using somthing like this '"../DBs/waiters.db"' and so on for others... but whatf of you try make multiple tables in a database file in tgat way you don need to have multiple databases and its the standard way,
hope it's help
When I executing the following function, I get the following response:
Failed to insert data into sqlite table: no such table: users
user_id = uuid.uuid4()
save_record.name = name
save_record.score = score
last_time = datetime.now()
try:
conn = sqlite3.connect('OnlineJeopardy.db')
cursor = conn.cursor()
print("Successfully Connected to OnlineJeopardy DB.")
sqlite_insert_query = """INSERT INTO users
(User_id, Name, Score, Last_time)
VALUES
(?, ?, ?, ?)"""
add_to_db = cursor.execute(sqlite_insert_query, (user_id, name, score, last_time))
conn.commit()
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table: ", error)
finally:
if (conn):
conn.close()
print("The SQLite connection is closed")
When I execute this query in DB Browser, with actual values instead of placeholders, it all goes well.
I've tried swapping placeholders to actual values (as below) within the query in sqlite3 but the outcome was the same.
conn = sqlite3.connect('OnlineJeopardy.db')
cursor = conn.cursor()
print("Successfully Connected to OnlineJeopardy DB.")
sqlite_insert_query = """INSERT INTO users
(User_id, Name, Score, Last_time)
VALUES
('ID-1337', 'Adam', 20, '2020-06-12 23:18:58')"""
add_to_db = cursor.execute(sqlite_insert_query)
conn.commit()
cursor.close()
I have testtable() function that works to create the table if necessary and list all the PDF file names in a column. However, when I execute my view() function, it prints an empty list. Am I missing something or just going about this in the wrong way?
import os, sys
import sqlite3
import csv
testdb = 'pdftestdir.db'
def testtable():
conn = sqlite3.connect(testdb)
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS test (name TEXT)')
path = os.listdir('/root/Desktop/PDF')
conn = sqlite3.connect(testdb)
cur = conn.cursor()
cur.execute('SELECT * FROM test')
exists = cur.fetchall()
for name in path:
if name.endswith('.pdf'):
if not exists:
cur.execute('INSERT INTO test VALUES (?)', (name,))
else:
pass
conn.commit()
conn.close()
def view():
conn = sqlite3.connect(testdb)
cur = conn.cursor()
cur.execute('SELECT * FROM test')
cur.fetchall()
rows = cur.fetchall()
conn.close()
print(rows)
You unnecessarily call cur.fetchall() without storing the returning value to a variable, and the cursor has already reached the end of the rows returned with that call, so the second time you call cur.fetchall() it no longer has any more rows to return.
You can fix this by simply removing the redundant call.
Change:
cur.fetchall()
rows = cur.fetchall()
to:
rows = cur.fetchall()
I'm writing unit tests to test my environment.
I have created tests such as:
def test_database_file_present_and_readable(self):
self.assertTrue(os.access(path_db_file, os.R_OK))
def test_connect_to_db(self):
conn = sqlite3.connect(path_db_file)
conn.close()
def test_create_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("CREATE TABLE test_table (id integer PRIMARY KEY, name text)")
conn.commit()
conn.close()
def test_insert_into_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("insert into test_table (name) values (?)", ["Test value"])
conn.commit()
conn.close()
def test_update_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("update test_table set id = 2 where id = ?", [1])
conn.commit()
conn.close()
def test_delete_from_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("delete from test_table where id = ?", [2])
conn.commit()
conn.close()
def test_if_test_table_is_empty(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
result = cur.execute("select exists(select 1 from test_table)").fetchall()
conn.commit()
conn.close()
self.assertTrue(result == 1)
def test_delete_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("drop table test_table")
conn.commit()
conn.close()
And during program execution order of tests is unknown - how to set the order or how to clean up database after creating tests with table creation?
You can get pointers about test method execution order here: Python unittest.TestCase execution order
One suggestion - if you are going for such testing, it's better to mock external dependencies like sqlite & test only the code you've written.