How to check if Record exists - python

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)

Related

Return results from Redshift database based on IF condition in Python

I need to extract results from a redshift database based on an IF condition written in Python.
Suppose I have a table with CustomerID, SHipment Number, Invoice Station, ect as columns in Redshift table, I want to get all the records from Redshift table if customer ID exists which should be checked with user input.
TABLE NAME = ShipmentInfo
COLUMNS = CustomerID, BillNumber, Invoicing Station, Charges, etc.
Python
import psycopg2
con=psycopg2.connect(dbname= 'datamodel', host='123',
port= '5439', user= 'bce', password= 'Ciz')
cur = con.cursor()
HWB = input("Enter the House Bill Number : ")
#if CustomerID = HWB:
cur.execute("SELECT source_system, file_nbr, file_date, CustomerID
FROM public.shipment_info where CustomerID = $HWB")
results = cur.fetchall()
cur.close()
con.close()
print(results)
Consider parameterization of user input value (else risk the infamous, Bobby Tables).
# PREPARED STATEMENT WITH PLACEHOLDER
sql = """SELECT source_system, file_nbr, file_date, CustomerID
FROM public.shipment_info
WHERE CustomerID = %s
"""
# BIND PARAM VALUES WITH TUPLE OF ONE-ITEM
cur.execute(sql, (HWB,))

Taking value from column in one sqlite3 table and inserting into another

I am trying to add a feature to my program where a teacher sets homework to users from a class they've made. There is a table for users where each user has a unique UserID, classname, firstname and surname. I am trying to take the userIDs of students who are in a certain class, and insert them into a HomeworkSet table. I am able to retrieve the userIDs successfully, but when I insert them into the HomeworkSet table, the values appear as (for example) ('2a1910e919a84230bfc2a7111160cade',), and I am not sure how I am meant to remove the brackets and apostraphes.
def Class_sethw():
homeworktoset = Homework_To_Set.get()
#print (homeworktoset)
conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor()
homeworkID = c.execute("SELECT HWID FROM HomeworkInfo WHERE HomeworkName = ?", (homeworktoset, )).fetchone()
print (homeworkID)
c.execute("SELECT UserID FROM users WHERE ClassName = ?", (ClassName_SetHWR, ))
homeworksetlist = c.fetchall()
print (homeworksetlist)
for i in (homeworksetlist):
#x = i
#firstname, lastname = x.split(" ")
c.execute('insert INTO HomeworkSet (HWID, StudentID)VALUES(?,?);', ((homeworkID[0]), str(i)))
conn.commit()
Label(sethw, text = "Homework Set!", fg = "GREEN").place(relx=0.205, rely=0.445, height=34, width=97)
This is the code I have used.
You should change this line:
for i in (homeworksetlist):
to:
for i in homeworksetlist:

SQLITE3 FROM table Select column WHERE Boolean statement

I have tried 3 different variations of sqlite3 statement to SELECT a data:
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
References for these statements are from 1 2. However, none of them worked. I suspect that I am doing something really silly but can't seem to figure this out.
I want to be able to print out the data of username "monkey". Appreciate any help to point out my silly mistake.
import sqlite3
import datetime
def get_user(connection, rows='all', username=None ):
"""Function to obtain data."""
#create cursor object from sqlite connection object
cursor = connection.cursor()
if rows == 'all':
print("\nrows == 'all'")
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()
for row in data:
print(row)
if rows == 'one':
print("\nrows == 'one'")
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
#cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
#cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
data = cursor.fetchone()
print('data = ',data)
cursor.close()
return data
def main():
database = ":memory:"
table = """ CREATE TABLE IF NOT EXISTS users (
created_on TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE
); """
created_on = datetime.datetime.now()
username = 'monkey'
email = 'monkey#gmail'
created_on1 = datetime.datetime.now()
username1 = 'monkey1'
email1 = 'monkey1#gmail'
# create a database connection & cursor
conn = sqlite3.connect(database)
cursor = conn.cursor()
# Insert data
if conn is not None:
# create user table
cursor.execute(table)
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on, email, username))
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on1, email1, username1))
conn.commit()
cursor.close()
else:
print("Error! cannot create the database connection.")
# Select data
alldata = get_user(conn, rows='all')
userdata = get_user(conn, rows='one', username=username )
print('\nalldata = ', alldata)
print('\nuserdata = ', userdata)
conn.close()
main()
Your table definition has the fields in order created_on, username, email but you inserted your data as created_on, email, username. Therefore the username of the first row was 'monkey#gmail'.
A good way to avoid this kind of mistake is to specify the columns in the INSERT statement rather than relying on getting the order of the original table definition correct:
INSERT INTO users (created_on, email, username) VALUES (?,?,?)

How do I confine the output of a fetchall() on my table to just the value?

I have the following function:
def credential_check(username, password):
conn = sqlite3.connect('pythontkinter.db')
c = conn.cursor()
idvalue = c.execute('''SELECT ID FROM userdetails WHERE username = "{0}"'''.format(username)).fetchall()
print(idvalue)
I wish to assign the value of ID in my userdetails table to the variable idvalue in the row where the inputted username = userdetails username, however when I use this fetchall() I get [('0',)] printed out rather than just 0.
How do I go about doing this?
Thanks
You can use fetchone() if you only want one value. However, the result will still be returned as a tuple, just without the list.
import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS testing(id TEXT)''')
conn.commit()
c.execute("""INSERT INTO testing (id) VALUES ('0')""")
conn.commit()
c.execute("""SELECT id FROM testing""")
data = c.fetchone()
print data
# --> (u'0',)
You can also use LIMIT if you want to restrict the number of returned values with fetchall().
More importantly, don't format your queries like that. Get used to using the ? placeholder as a habit so that you are not vulnerable to SQL injection.
idvalue = c.execute("""SELECT ID FROM userdetails WHERE username = ?""", (username,)).fetchone()

Product ID not being added in my database

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.

Categories

Resources