Enter data into a SQL table in python? - python

I'm making a program that connects to a SQL database for me to enter in data. Instead of entering data into the table manually, I wanted to make a program do it. So it's asks me a series of questions, then inputs the answers into the table. I am not sure how to do that. My issue is at the end with the cursor execute.
I am not sure how I can incorporate the input answers into that execute function. Would it be something like this? The .format is showing up as a string, so I am not sure how to implement this.
VALUES
('{}'.format(category), '{}'.format(description), '{}'.format(date), '{}'.format(price), '{}'.format(vehicle))
Here is the code below:
import time
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TJDESKTOPPC;'
'Database=carparts;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM carparts.dbo.modifications
''')
conn.commit()
# Menu starts below
database = "carparts"
print("Welcome to the program!")
print()
print("You are connected to {} database".format(database))
print()
print()
print("The current columns in the table are...")
print()
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TJDESKTOPPC;'
'Database=carparts;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM carparts.dbo.modifications where 1=2')
headers = [i[0] for i in cursor.description]
print(headers)
print()
print("Categories are: engine, suspension, exhaust, or transmission")
print()
category = str(input("Please enter category: "))
print()
description = str(input("Please enter the description of the part: "))
print()
purchase_date = input("Please enter the purchase date in (YYYY-MM-DD): ")
print()
price = int(input("Please enter the price amount: "))
print()
vehicle = str(input("What vehicle is this for? (Model): "))
print()
print("Thanks!")
time.sleep(3)
print("\n" * 5) # This will the clear screen of any previous code
print("Adding the category, description, purchase date, price, and vehicle to the table...")
time.sleep(2)
cursor.execute('''
INSERT INTO carparts.dbo.modifications (category, description, purchase_date, price,
vehicle)
VALUES
('exhaust', 'Flowmaster Cat-back Exhaust', '2015-12-08', '551', 'focus_st')
''')
conn.commit()
The snippet above for INSERT INTO actually works, but I need to put the values in manually how it is. So how do I get the variable input (category, description, date, etc) in that string?

Try this,
Here you need to provide your variable data you want to insert and also need to add {} in single quotes like this '{}'.
So that your after providing value in format "'{}'".format("category_input") is looks like 'category_input' and it doesn't effect if you have a number.
cursor.execute('''INSERT INTO carparts.dbo.modifications (category, description,
purchase_date, price, vehicle) VALUES ('{}', '{}', '{}', '{}', '{}')'''.format(category, description, purchase_date, price, vehicle))

Related

Issues with IF statements and Pypyodbc

I am brand new to Python and know very little. I have connected my MS-Access file to my python using Pypyodbc. I am attempting to query with it using a user input however, I need it to be able to change based on the input of the user rather than having lots of hard-coded options. Here is the code and any help is greatly appreciated. Thanks.
Side note: I would be adding more options to this if statement in the future (a total of 5 accepted user inputs)
import pypyodbc
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\DB\FILM_SMITH.accdb;')
cursor = conn.cursor()
input("What would you like to search for? ")
if input == "genre":
genre = input("Please input the required genre: ")
connstring = "select * from Films where Genre = " + genre
if input == "rating":
rating = input("Please input the required age rating: ")
connstring = "select * from Films where BBFC = " + rating
else:
print("Invalid Entry")
for row in cursor.fetchall():
print (row)
First, your code is prone to SQL injection attacks. You should pass the parameter dynamically, instead of putting it inside the string. See this for example.
Now to your actual question. If you want to avoid some code repetition, you can make a list of possible fields. You should have a way to restrict the possible fields, otherwise the user might provide an invalid field. Here is an example:
available_fields = ['genre', 'rating', 'another_field']
fld = input('What field would you like to search for?')
assert fld in available_fields, 'Invalid field'
value = input('Please enter a value you want to search for: ')
query = f'select * from Films where {fld} = ?'
# Now run the query with *value* as a dynamic parameter
Your requirements might vary, so probably there is a better solution for your case. But that should help, I hope.
Here is another way of doing it to prevent code duplication using a dictionary.
the dictionary is structured like this
"key_you_want_to_search":["Question_you_want_the_user_to_answer","Name_of_your_SQL,column"]
import pypyodbc
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\DB\FILM_SMITH.accdb;')
cursor = conn.cursor()
dictionary = {"genre": ["Please input the required genre: ", "Genre"],
"rating": ["Please input the required age rating: ", "BBFC"]}
user_input = input("What would you like to search for? ")
if user_input in dictionary:
temp = input(dictionary[user_input][0])
connstring = f"select * from Films where {dictionary[user_input][1]} = {temp}"
else:
print("Invalid Entry")
for row in cursor.fetchall():
print(row)

sorry for that kind of question but i must ask . How to create a table in SQLITE to ask me what to call a table

E.g. After launching the program:
It is in interactive mode
We are asked what name we want to create the database with;
After creating the database, the program asks us under what name to create the table in the database;
In the next step, the program asks us how many columns the table should have;
Enter the names of the mentioned number of columns and their types interactively;
Finally, create a database and a table with the columns indicated in it;
import sqlite3
connection = sqlite3.connect(input("Enter the name for base: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
columns_name = []
columns_amount = int(input("Enter amount of coulms and name them: "))
for item in range(columns_amount):
item = input("input theme mane of column: ")
columns_name.append(item)
cursor.execute("DROP TABLE IF EXISTS "+table_name+"" )
cursor.execute("CREATE TABLE IF NOT EXISTS "+ table_name +" ("+columns_name[0]+" INTEGER PRIMARY KEY AUTOINCREMENT ,Name TEXT, "+columns_name[1]+" TEXT, "+columns_name[2]+" TEXT, "+columns_name[3]+" TEXT )")
connection.commit()
You can just create the sql string for table creation inside the loop like -
import sqlite3
connection = sqlite3.connect(input("Enter the name for database: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
sql_string = "CREATE TABLE IF NOT EXISTS {} (".format(table_name)
columns_amount = int(input("Enter amount of columns: "))
for i in range(columns_amount):
column = input("input the name of column {}: ".format(i + 1))
datatype = input("input the type of column: ")
# You may want to check here whether column name and data type is valid or not
sql_string += "{} {},".format(column, datatype)
# remove the last extra comma
sql_string = sql_string[:-1]
sql_string += ")"
print(sql_string)
cursor.execute("DROP TABLE IF EXISTS {}".format(table_name))
# Finally create the table
cursor.execute(sql_string)
connection.commit()
Your code will not work because during table creation you are assuming that there are 3 columns which may not be true. So accessing those indices of columns_name might throw exception.

Ask for user input and insert in DB in python with sqlite3

At the moment I try to ask the user for input in Python, to enter some information (here: expenseID, expense, categoryID, date). But I do not know were to start. No input validation is necessary at this step.
I managed to access my database and INSERT something manually. I tried several ways of the python input function but cannot use it as a placeholder in the SQL string.
import sqlite3
with sqlite3.connect('Expenses.sqlite') as conn:
# INSERT MANUALLY
script = "INSERT INTO Expense (ExpenseId, Amount, CategoryId, Date) VALUES ('103', '43625.5', '5', '2019-01-20');"
conn.execute(script) # execute the script
conn.commit() # commit changes to the file
# INSERT USER INPUT ???
pass
This is my idea:
with sqlite3.connect('Expenses.sqlite') as conn:
amount = input("What is the amount?")
script = "SELECT * FROM Category;"
conn.execute(script)
print(script)
category = input("What is the category?")
exp_ID = "SELECT LAST ExpenseId FROM Expense);"
date = datetime.date.today()
script = "INSERT INTO Expense (ExpenseId, Amount, CategoryId, Date) VALUES (exp_ID, amount, category, date);"
conn.execute(script)
conn.commit()
pass
Finally I want to achieve that the user is asked for amount of expense, and afterwards for expense category. ExpenseID and date should be added automatically. Date format is year-month-day. Thank you very much for advice.
Use the input function to retrieve the user input
user_input = input("Expense Amount: ")
Then use placeholders with sqlite3
sql = "INSERT INTO TABLE (COLUMN) VALUES (?)"
conn.execute(sql, (user_input,))
**in response to your edit
You need to add placeholders instead of the variable names.
Something like this:
script = "INSERT INTO Expense (ExpenseId, Amount, CategoryId, Date) VALUES (?, ?, ?, ?);"
conn.execute(script, (exp_ID,amount,category,date))

Use a query in sqlite value - python

Does anyone know how to execute a query inside a value in python sqlite
The eroor i am getting is:
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
my code is here:
Name = input("Enter the name of the product you want to purchase: >>")
item = Name
qty = input("Enter the Quantity of the product you want to purchase: >>")
today = date.today()
cursor = db.cursor()
cursor.execute("SELECT CatID from Products where Name=?",(Name,))
result = cursor.fetchall()
confirm = input("are you sure you want tot buy this product (y/n): >>" )
if confirm == "y":
### In this query where it says result i want to execute the data from the result query
cursor.execute("INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) Values(?,?,?,?,?)",(Username,result,today,qty,Name))
db.commit()
print("Product purchased. Thankyou for your order")
cursor.execute("UPDATE Products SET Qty = (? -1) where Name = ?",(qty,item,))
else:
print("The program will now terminate")
You can also iterate over result:
for row in result:
cursor.execute(
"INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) SELECT CatID,?,?,?,? FROM Products WHERE Name=?",(Username,row,today,qty,Name))
db.commit()

Calling three tables to insert data. (sqlite3/python)

I have normalised three tables (Product, ProductType and ProductGender) and I'm looking to call them in my main program so that the user can successfully enter values and the data be stored in the correct table.
Here are the SQL tables being created
def create_product_table():
sql = """create table Product
(ProductID integer,
Name text,
primary key(ProductID))"""
create_table(db_name, "Product", sql)
def create_product_type_table():
sql = """create table ProductType
(ProductID integer,
Colour text,
Size text,
Gender text,
AmountInStock integer,
Source text,
primary key(ProductID, Colour, Size, Gender)
foreign key(Gender) references ProductGender(Gender)
foreign key(ProductID) references Product(ProductID))"""
create_table(db_name, "ProductType", sql)
def create_product_gender_table():
sql = """create table ProductGender
(Gender text,
Price text,
primary key(Gender))"""
create_table(db_name, "ProductGender", sql)
Here are the SQL subroutines
def insert_data(values):
with sqlite3.connect("jam_stock.db") as db:
cursor = db.cursor()
sql = "insert into Product (Name, ProductID) values (?,?)"
cursor.execute(sql,values)
db.commit()
def insert_product_type_data(records):
sql = "insert into ProductType(Amount, Size, Colour, Source) values (?,?,?,?)"
for record in records:
query(sql,record)
def insert_product_gender_data(records):
sql = "insert into ProductGender(Gender, Price) values (?,?)"
for record in records:
query(sql, records)
def query(sql,data): #important
with sqlite3.connect("jam_stock.db") as db:
cursor = db.cursor()
cursor.execute("PRAGMA foreign_keys = ON") #referential integrity
cursor.execute(sql,data)
db.commit()
Below is the code where the user will enter the values.
if ans=="1": #1=to option 'Add Stock'
a = input("Enter Gender: ")
b = float(input("Enter Price: "))
c = int(input("Enter ProductID: "))
d = input("Enter Name: ")
e = input("Enter Size: ")
f = input("Enter Colour: ")
g = input("Enter Source: ")
h = input("Enter Amount: ")
#code calling tables should be here
Help is gratefully appreciated. Seriously not sure how to link the 3 tables with the user's input.
This is what I did before I normalised the database. So the one table in 'Product' would be updated instead of adding an already existing product. Obviously that has changed now, since I've created two new tables but I can't successfully add a product let alone edit one.
def update_product(data): #subroutine for editing stock
with sqlite3.connect("jam_stock.db") as db:
cursor = db.cursor()
sql = "update Product set Name=?, Price=?, Amount=?, Size=?, Colour=?, Source=?, Gender=? where ProductID=?"
cursor.execute(sql,data)
db.commit()
Given the code you show above, and assuming (BIG assumption, see later!) that the user never enters data for existing records, the following code should do it:
query('insert into Product (Name, ProductID) values (?,?)',
[d, c])
query('insert into ProductGender (Gender, Price) values (?,?)',
[a, b])
query('insert into ProductType (ProductID, Colour, Size, Gender, '
AmountInStock, Source) values (?,?,?,?,?,?)',
[c, f, e, a, h, g])
Your use of arbitrary single-letter variable names makes this very hard to follow, of course, but I think I got the correspondence right:-).
Much more important is the problem that you never tell us what to do if the user enters data for an already existing record in one or more of the three tables (as determined by the respective primary keys).
For example, what if Product already has a record with a ProductID of foobar and a Name of Charlemagne; and the user enters ProductID as foobar and a Name of Alexandre; what do you want to happen in this case? You never tell us!
The code I present above will just fail the whole sequence because of the attempt to insert a new record in Product with an already-existing primary key; if you don't catch the exception and print an error message this will in fact crash your whole program.
But maybe you want to do something completely different in such cases -- and there are so many possibilities that we can't just blindly guess!
So please edit your Q to clarify in minute detail what's supposed to happen in each case of primary key "duplication" in one or more table (unless you're fine with just crashing in such cases!-), and the SQL and Python code to make exactly-that happen will follow. But of course we can't decide what the semantics of your program are meant to be...!-)

Categories