Hi I have created a database wnad when I try to insert data into it everything is added accept for the product ID. Here is the code I have.
Database creation,
import sqlite3
def create_table(db_name,table_name,sql):
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name=?",(table_name,))
result = cursor.fetchall()
keep_table = True
if len(result) == 1:
response = input("The table {0} already exists, do you want to recreate it (y/n)?: ".format(table_name))
if response == "y":
keep_table = False
print("The table {0} will be recreated - all existing data will be lost.".format(table_name))
cursor.execute("drop table if exists {0}".format(table_name))
db.commit()
else:
print("The existing table was kept")
else:
keep_table = False
if not keep_table:
cursor.execute(sql)
db.commit()
if __name__ == "__main__":
db_name = "coffee_shop.db"
sql = """create table Product
(ProductID intiger,
Name text,
Price real,
primary key(ProductID))"""
create_table(db_name, "Product", sql)
and then I was using this to insert data
import sqlite3
def insert_data(values):
with sqlite3.connect("coffee_shop.db") as db:
cursor = db.cursor()
sql = "insert into Product (Name, Price) values (?,?)"
cursor.execute(sql,values)
db.commit()
name = input("what is the product called?: ")
value = float(input("How much does it cost?: "))
if __name__ == "__main__":
product = ("{0}".format(name),"{0}".format(value))
insert_data(product)
And this is what my database ends up like, without a product id:
You gave your ProductID the type intiger; that is not a type SQLite recognizes. Correct that to be integer and the column will auto-increment.
See SQLite Autoincrement for more details.
Related
I'm trying to solve this exercise, and I have no clue why my SQLite DB won't update. Here is what I tried. Any ideas would be much appreciated:
Also, I forgot how to keep the program running, I mean to keep showing the user the options he has :(
import sqlite3
conn = sqlite3.connect("Books")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS Books(
id INT PRIMARY KEY,
title TEXT,
year INT);
""")
user_input = input ("Dear User, you have the following two options, two and only two (case sensitive): \n\t 1. INSERT \n\t 2. SHOW BOOKS \nPlease insert your comamnd here: <<< ")
if user_input == "1. INSERT":
book_id = input("Book id: ")
book_title = input("Book title: ")
book_year = input ("Book year of publication: ")
cursor.execute
(""" INSERT INTO Books (id, title, year) VALUES (?,?,?)
""", (book_id, book_title, book_year))
conn.commit()
print("Book inserted succesfully!")
elif user_input == "2. SHOW BOOKS":
cursor.execute("SELECT * FROM Books;")
all_results = cursor.fetchall()
print(all_results)
else:
print("Not a valid command. Try again! It's all case sensitive in Python, u know...")
if (conn):
conn.close()
I have an issue returning a string from my database query.
First step was to create a database:
def create_database():
# database setup
try:
con = sqlite3.connect('db/mydb.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS user (id INTEGER NOT NULL PRIMARY KEY, balance REAL NOT NULL, text TEXT NOT NULL)')
con.commit()
con.close()
except Error as e:
print('Failed to setup database.\n' + e)
exit(1)
def get_connection():
try:
con = sqlite3.connect('db/mydb.db')
return con
except:
print('Unable to connect to database. Please try again later.\n')
exit(1)
My second step was creating a user and add him with INSERT to my database:
def create_user(user_id : int):
balance = 0.0; # base unit = USD
text = create_text()
# connect to database
con = get_connection()
cur = con.cursor()
cur.execute('INSERT INTO user (id, balance, text) VALUES (?, ?, ?)', (user_id, balance, text))
database = cur.execute('SELECT * FROM user').fetchone()
print(database)
con.commit()
con.close()
def create_text():
# do some stuff which creates my text
# the text is something like 'LNURL...'
return text
This is how the result of my database query looks like:
(393120847059091456, 0.0, 'LNURL1DP68GURN8GHJ7URP09JX7MTPDCHXGEF0D3H82UNVWQHKZURF9AMRZTMVDE6HYMP0XGMQA9V7RT')
If I try to query this database for my text it returns nothing/None. My print(text) just produces an empty new line.
def get_text(user_id : int):
# connect to database
con = get_connection()
cur = con.cursor()
cur.execute('SELECT text FROM user WHERE id=?', (user_id,))
text = cur.fetchone()
con.commit()
con.close()
print(text)
return text
I think my sqlite database used 32bit int values by default. So forcing it to use 64 bit when creating the table fixed my issue:
cur.execute('CREATE TABLE IF NOT EXISTS user (id INT8 PRIMARY KEY NOT NULL, balance REAL NOT NULL, text TEXT NOT NULL')
Than I can return my result of the query with this: return text[0]
When I create the DataBase CURRENT_users.db:
import sqlite3
conn = sqlite3.connect('CURRENT_users.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
email TEXT NOT NULL,
created_in DATE NOT NULL,
password TEXT NOT NULL
)
""")
print("Success! DATABASE created with success!")
conn.close()
import UserLoginUI_Part2_Tes
t1
And I insert the DATA:
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO users (id, nome, email, created_in, password)
VALUES (001, "Renatinho", "renato.lenon#Outlook.com", 2005-4-21, "Plugxyvj9");
""")
conn.commit()
print("A new user has been incremented! Now,have fun!!!")
conn.close()
import UserInterface
In "UserInterface", I type "Renatinho" (that's my NOME data),it seems like that "IF" doesn't work!!
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
user_INFO = cursor.execute(""" SELECT nome FROM users; """)
user_in_SCRIPT = str(input("Your credentials: USERNAME: \n>>>"))
logged_in = False;
if user_in_SCRIPT == user_INFO:
print("You are logged in! Enjoy your new account...")
logged_in = True;
else:
print("Error: Not a valid user or USERNAME!!")
conn.close()
And it ever shows me the ELSE "command block"..
Please,who can help me?
Thanks for everything...
PRINT OF THE ERROR:
You've called SQL SELECT but you need to fetch the data.
cursor.execute("SELECT nome FROM users")
user_INFO = cursor.fetchone()
This would return a tuple, so to get the string inside, take the zero index:
if user_in_SCRIPT == user_INFO[0]:
print("You are logged in! Enjoy your new account...")
logged_in = True
BTW, you're in Python, not JavaScript. You don't need to end statements with semicolons. :-)
I want to able to check if a record exists in the DB with a specific 'ID' and create one if it does not have one( i.e, Doesnt exist) Like so...
I would also like to fetch "Num" For a specific record after it has been updated.
import sqlite3 as lite
db = lite.connect("test.db")
id_to_be_added = "123456789101112"
db.execute("CREATE TABLE USERS (ID TEXT, NUM INT)")
Query = "{ SOMETHING IN SQL }" # This returns either True or False
if Query:
db.execute("UPDATE USERS SET NUM = NUM + 1 WHERE ID = {};".format(id_to_be_added))
else:
db.execute("INSERT INTO USERS ({}, 0)".format(id_to_be_added))
num_to_be_printed = db.execute("SELECT NUM FROM USERS WHERE ID = {}".format(id_to_be_added))
print("{0} has {1}").format(id_to_be_added, num_to_be_printed)
Either create a primary key and use INSERT OR REPLACE query, or use a SELECT query.
I was able to solve it using cur.fetchall()
import sqlite3 as lite
db = lite.connect(r"test.db")
id_tba = r"123456789101112"
cur = db.cursor()
cur.execute("SELECT * FROM USERS WHERE ID = {}".format(id_tba))
if len(cur.fetchall()) > 0:
db.execute("UPDATE USERS SET NUM = NUM + 1 WHERE ID = {};".format(id_tba))
else:
db.execute("INSERT INTO USERS ({}, 0)".format(id_tba))
num_to_be_printed = db.execute("SELECT NUM FROM USERS WHERE ID = {}".format(id_tba))
print("{0} has {1}").format(id_tba, num_to_be_printed)
def makeProductTable():
"""This creates a database with a blank table."""
with connect("products.db") as db:
cursor = db.cursor()
cursor.execute("""
CREATE TABLE Product(
ProductID integer,
GTIN integer,
Description string,
StockLevel integer,
Primary Key(ProductID));""")
db.commit()
def editStockLevel():
with connect("products.db") as db:
cursor = db.cursor()
Product_ID=input("Please enter the id of the product you would like to change: ")
Stock_Update=input("Please enter the new stock level: ")
sql = "update product set StockLevel = ('Stock_Update') where ProductID = ('Product_ID');"
cursor.execute(sql)
db.commit()
return "Stock Level Updated."
The first function is used to make the table and it shows my column titles, the second function is needed to update a specific value in the table.
But when this is ran the inputs are executed, however when all show all the products in the table the value for stock level doesn't change.
So I think the problem has something to do with the cursor.execute(sql) line.
Or something like this?
cur.execute("UPDATE Product set StockLevel = ? where ProductID = ?",(Stock_Update,Product_ID))
Yes; you're passing literal strings, instead of the values returned from your input calls. You need to use parameters in the statement and pass thme to the execute call.
sql= "update product set StockLevel = %s where ProductID = %s;"
cursor.execute(sql, (Stock_Update, Product_ID))