Issues with IF statements and Pypyodbc - python

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)

Related

Take user input from Python to SQL query

I am creating a store front page where the user will be able to search for items inside of an SQL data base. I am having issues with the python logic where I am trying to use the WHERE logic to find what the user hass entered. Here is my code:
username = input("Enter your username >>> ")
password = input("Enter your password >>> ")
try:
cursor.execute('SELECT * FROM users ORDER BY email')
except:
print("The database does not exist")
else:
list_of_users = cursor.fetchall()
def login(email: str, pwd: str, list_of_users: [()]) -> bool:
for db_email, db_pwd in list_of_users:
if (email == db_email) and (pwd == db_pwd):
return True
return False
#----------Storefront----------#
while login(username, password, list_of_users) == True:
search_bar = input("Enter what item you would like to look up >>> ")
sql = "SELECT * FROM item_in_stock WHERE item_name = "
cursor.execute(sql , search_bar)
for row in iter(cursor.fetchone, None):
print(row)
also if someone has a better way of testing to see if what I get out of the table is the correct value that I am looking for instead of using
for row in iter(cursor.fetchone, None):
print(row)
then please do share as I do not understand what that for loop is doing.
When I run the program, this is what I get:
Enter your username >>> joe#gmail.com
Enter your password >>> qwerty
Enter what item you would like to look up >>> Jumper
Traceback (most recent call last):
File "C:/Users/jerem/PycharmProjects/assignment_core/main.py", line 30, in <module>
cursor.execute(sql , search_bar)
sqlite3.OperationalError: incomplete input
No clue how to fix this.
cursor.execute as you are using it accepts two parameters, sql and parameters. I believe, according to sqlite docs and sqlite parameter reference, that you should define your string sql with sql = "SELECT * FROM item_in_stock WHERE item_name = ?" and pass parameters into cursor.execute in a tuple.
All in all, you might want to try something along the lines of:
while login(username, password, list_of_users) == True:
search_bar = input("Enter what item you would like to look up >>> ")
sql = "SELECT * FROM item_in_stock WHERE item_name = ?"
cursor.execute(sql, (search_bar))
for row in iter(cursor.fetchone, None):
print(row)

taking Input of datatype and its size from user to modify column in a table in Python database

I am a newbie to Sql and database concepts. so I am trying to make a program which does the basic tasks done by replacing the idea of entering commands by using functions in MySQL( like creating a table in database, adding records, modifying table etc). I now want to take input from user which include column name, its datatype, its size so that user can decide the basic structure of a new column.
So , I came across something called string formatting which I used a bit to enter variables into the Sql commands. so I tried using this concept in this case. But it gives syntax error.
Can somebody suggest me a solution to this and tell me my mistake.
I apologize for my bad grammar
Thanks
here is the code
##importing mysql connector
import mysql.connector
## Creating connection object
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "milkshake#343",
database = 'practice'
)
## defining a cursor object
cursor_obj = mydb.cursor()
##creating a table (uncommnent to edit and execute)
def table_create():
cursor_obj.execute("CREATE TABLE test3(name VARCHAR(50),ageINT unsigned,person_id int PRIMARY KEY AUTO_INCREMENT)")
## Describing the table (uncommnent to edit and execute)
def table_desc():
cursor_obj.execute("describe test3")
for x in cursor_obj:
print(x)
##creating a function to enter values into the table
def inputer():
#taking records from user to enter in the table
name = input("please enter the name to enter into the table:")
age = int(input("please enter the age to enter into the table:"))
#Entering values into the table
cursor_obj.execute('insert into test3 values(%s,%s)',(name,age))#you may change table name here if you want
##creating a comitt option
def commit():
mydb.commit()
##function to display the whole content of the table
def whole_table():
cursor_obj.execute("select * from test3")
for x in cursor_obj:
print(x)
##adding column into the table
def column_add():
new_column = input("Enter the name of the new column:")
data_type = input("Enter the data type of new column:")
size = int(input("Enter the size of the new column:"))
cursor_obj.execute("alter table test3 add column %s %s(%s)",(new_column,data_type,size))
column_add()
commit()
I am going to add more functions in this

Enter data into a SQL table in 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))

python dictionary to sqlite insert

As I m reading about SQLLite3 and Python, I tried this simple dictionary to DB approach. I have tried a few stackoverflow forums but now able to figure out how to get this data from dictionary to database and then print it. Code below:
import sqlite3
user_dir={}
#connect a built in function to connect or create db
conn=sqlite3.connect('phonebook.db')
#Create a cursor function which allows us to do sql operations
crsr=conn.cursor()
#Create a Table
#crsr.execute(""" Create Table phonebook(
# f_name text,
# phone text)
# """)
def create_user():
while True:
rsp=input('Create new user: Y/N ?')
if rsp=='y':
f_name = input('Enter first name: ')
#First name cannot be empty
while (len(f_name)==0):
print('First name cannot be empty')
f_name = input('Enter first name: ')
phone = input('Enter phone number: ')
user_dir[f_name]=phone
#crsr.execute("INSERT INTO phonebook VALUES (?,?)", [user_dir["f_name"], user_dir["phone"]])
#crsr.executemany("INSERT INTO phonebook VALUES (?,?)", user_dir)
columns = ', '.join(user_dir.keys())
sql = "INSERT INTO phonebook VALUES (?,?)" % ('phonebook', columns)
crsr.execute(sql, user_dir.values())
if rsp=='n':
break
crsr.execute("SELECT * from phonebook")
print(crsr.fetchall())
Errors are different for each commented out lines. Thanks for your time and help.

Trying to search a column on SQLite Python so that it only returns the information searched

New to Python and Databases
I have a database table set up with a column of usernames. I want the user to be able to search through the table via a raw_input and only return the values which are associated with that user name.
E.g. user searches for Bill and it only displays Bill's records ordered by a specified column
This is what I have so far but its obviously VERY wrong, hope someone can help:
def find_me(db, column_name):
db = sqlite3.connect(db)
cursor = db.cursor()
name = raw_input("Please enter your username: ")
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
cursor.execute("SELECT * FROM username ORDER BY "+column_name+" ASC")
name = cursor.fetchone()
next = cursor.fetchone()
Thank you in advance
You want to make the query similar to the following:
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
This uses query parameters, so it's correctly escaped for the data provided. Then just adapt this to SELECT * and whatever else you want from the result.
Try working with this:
name = raw_input("Please enter your username: ")
query = "SELECT * FROM username WHERE name=? ORDER BY {0}".format(column_name)
cursor.execute(query, (name,))
for row in cursor:
print row

Categories