Python output is blank when i execute the following code: - python-3.x

This program is a banking system. It connects to an online database which contains customer details and transaction details. However, when I execute the code, I get a blank output in python 3.4.0 shell:
import pyodbc
cnxn = pyodbc.connect('Driver={SQL Server};'
'Server=***;'
'Database=***;'
'uid=***;pwd=***')
cursor = cnxn.cursor()
def MainMenu():
print('##############################\n\tWelcome to the XYZ Banking System\n##############################')
print()
print('PLEASE ENTER THE NUMBER CORRESPONDING TO YOUR DESIRED COMMAND IN THE PROMPT BELOW : \n\t1.ACCESS CUSTOMER DETAILS\n\t2.ACCESS TRANSACTION PORTAL\n##############################')
print()
var_UserInput=input('>>>')
if var_UserInput=='1':
return CustomerPortal()
def CustomerPortal():
cursor.tables()
rows = cursor.fetchall()
for row in rows:
print (row.customer)
MainMenu()

Try this. I've made a few changes:
Moved the connection string into the function
Modified the code to be closer to PEP-8 https://www.python.org/dev/peps/pep-0008/
Fixed indentation
Here's the code.
import pyodbc
def main_menu():
print('##############################\n\tWelcome to the XYZ Banking System\n##############################')
print()
print('PLEASE ENTER THE NUMBER CORRESPONDING TO YOUR DESIRED COMMAND IN THE PROMPT BELOW : \n\t1.ACCESS CUSTOMER DETAILS\n\t2.ACCESS TRANSACTION PORTAL\n##############################')
print()
var_user_input=input('>>>')
if var_user_input=='1':
return customer_portal()
def customer_portal():
cnxn = pyodbc.connect('Driver={SQL Server};'
'Server=***;'
'Database=***;'
'uid=***;pwd=***')
cursor = cnxn.cursor()
cursor.tables()
rows = cursor.fetchall()
for row in rows:
print (row.customer)
cursor.close()
if __name__ == "__main__":
main_menu()
Good luck!

Related

How to do validation in python?

I am making a gui for employee management system using python tkinter and sqlite3.
In this gui user can add, view, delete amd update employee info.
def save():
con = None
try:
con = connect("pro.db")
cursor = con.cursor()
sql = "insert into Employee values('%d', '%s', '%f')"
id = int(aw_ent_id.get())
name = aw_ent_name.get()
lenstring = False
while not lenstring:
if len(name) >= 2:
lenstring = True
else:
showerror("error","Enter atleast 2 letters")
break
salary = float(aw_ent_salary.get())
cursor.execute(sql%(id, name, salary))
con.commit()
showinfo("success", "record added")
aw_ent_id.delete(0, END)
aw_ent_name.delete(0, END)
aw_ent_salary.delete(0, END)
aw_ent_id.focus()
except Exception as e:
con.rollback()
showerror("issue", e)
finally:
if con is not None:
con.close()
the code is running but i am getting some errors in validating name and salary.
for name i have done validating but its not working. I am getting an error
the data is getting saved even after getting error.
What should i do to make it right?
It is better to:
validate the inputs before saving to database
raise exception if len(name) is less than 2 instead of using while loop checking (actually the while loop is meaningless)
use placeholders to avoid SQL injection
Below is updated save():
# avoid using wildcard import
import tkinter as tk
from tkinter.messagebox import showinfo, showerror
import sqlite3
...
def save():
con = None
try:
# validate inputs
# use emp_id instead of id because id is built-in function
emp_id = int(aw_ent_id.get().strip()) # raise ValueError if not a valid integer
name = aw_ent_name.get().strip()
if len(name) < 2:
raise Exception('Name too short, at least 2 letters')
salary = float(aw_ent_salary.get().strip()) # raise ValueError if not a valid float number
# validations on inputs are passed, try saving to database
sql = 'insert into Employee values (?, ?, ?)' # use placeholders to avoid SQL injection
con = sqlite3.connect('pro.db')
cursor = con.cursor()
cursor.execute(sql, (emp_id, name, salary))
con.commit()
showinfo('Success', 'Employee added')
aw_ent_id.delete(0, tk.END)
aw_ent_name.delete(0, tk.END)
aw_ent_salary.delete(0, tk.END)
aw_ent_id.focus_set()
except Exception as e:
if con:
con.rollback()
showerror("Error", e)
finally:
if con:
con.close()
...

Python3 - Database sqlite3 - sqlite3.OperationalError: no such column:

I am trying to create a small and simple accountancy program, here is my code:
import sqlite3 as lite #db
import sys #db
from pathlib import Path #check file exists
successful_login = False
def login_process():
print("Welcome to your accountance program, write your username: ")
user = input()
my_file = Path("./%s" % (user,))
if my_file.is_file():
con = lite.connect(user)
main_loop()
else:
con = lite.connect(user)
print("Write the name of your bank account: ")
bankaccount = input()
print("Write how much money do you have on it: ")
starting_money = int(input())
print(starting_money)
with con:
cur = con.cursor()
cur.execute("CREATE TABLE Bank(Name TEXT, Money INT)")
cur.execute("INSERT INTO Bank VALUES (%s,%s)" % (bankaccount,starting_money))
main_loop()
And here is the error:
Why is this happening ?
Thank you !
From the python sqlite API doc:
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
(And examining this INSECURE example carefully should illuminate what is the error in this program).
Suggest you use the doc to learn how to use placeholders. It is an important habit to develop.

Code not being executed, program jumps out of the loop and waits for another command

I'm trying to return 'search not found' when nothing is found in the database, but the program just jumps out the loop
I tried checking for 0 or '', but realized that the database returns NoneType. I'm checking for None now, but the code still does not get executed.
def search():
def searchmenu():
print('')
ans=str(input('Make another [s]earch or return to the [m]ain menu: '))
ans=ans.lower()
if ans=='s':
Inventory.search()
elif ans=='m':
menu=MainMenu()
menu.menuops()
else:
print('invalid menu option')
searchmenu()
mydb = mysql.connector.connect(host="localhost", user="root", password="", database="pharmd")
cursor = mydb.cursor()
query=str(input("Search: "))
if query != "":
cursor.execute('SELECT * FROM drugs WHERE name LIKE "%'+query+'%"')
results=cursor.fetchall()
if results != None:
for data in results:
print('found!')
print(data)
searchmenu()
else:
print('No results found')
else:
print('Please enter a valid search!')
print('')
Inventory.search()
The problem is that cursor.fetchall() doesn't return None but an empty tuple ().
You can check cursor.rowcount for empty result according to the answer for this question.

Displaying sqlite3 data into Treeview

I am writing some code that shows a list of food with their information.
My code:
-connects to data base and gets items successfully
-loops correctly
Problem:
-If the name of my product is one word (ex:eggs) my code displays everything in the correct column
-If the name of my product is two or more words (ex:frosted flakes) my code displays 'frosted' on first column then 'flakes' in next columns which is incorrect
from tkinter import ttk
import tkinter as tk
import sqlite3
try:
from Tkinter import *
except ImportError:
from tkinter import *
def View():
db = sqlite3.connect("food_data.db")
cursor = db.cursor()
cursor.execute("SELECT name, quantity, expdate FROM food ORDER BY expdate ASC")
for row in cursor:
disp=('{0} {1} {2}'.format(row[0], row[1], row[2]))
tree.insert("",tk.END, values=disp)
db.close()
root = tk.Tk()
root.geometry("800x480")
tree = ttk.Treeview(column=("column1","column2","column3"),show='headings')
tree.heading("#1", text="Name")
tree.heading("#2", text="Quantity")
tree.heading("#3", text="Expiration Date")
tree.pack()
b2 = tk.Button(text="view data", command=View)
b2.pack()
root.mainloop()
It is suppose to successfully display items with multiple words in their name onto one column and not carry to the next one.
def View():
db = sqlite3.connect("food_data.db")
cursor = db.cursor()
cursor.execute("SELECT name, quantity, expdate FROM food ORDER BY expdate ASC")
for row in cursor:
# disp=('{0} {1} {2}'.format(row[0], row[1], row[2]))
tree.insert("",tk.END, values=(row[0], row[1], row[2]))
db.close()
Do it this way rather you have to insert the content in the treeview as tuple or list after iterating over it.
tree.insert("",tk.END, values=(row[0], row[1], row[2]))

How to print all the highest value places

I cannot figure out how to get python to print all the highest values as it only prints the first one it encounters.
It takes standard input from a file that has on a few lines the following:
89 Michael Dunne (grade name)
I know I can use the zip function but I cannot figure out how only print the name from it
If I add "highstudents = sorted(zip(grade,name),reverse=True)" it sorts from high to low but I do not know how to filter the name out as it prints as "(89, 'Pepe')"
The code below is the following attempt so far.
import sys
def topgrade(x):
s = max(x)
return s
def main():
s = sys.argv[1]
grade=[]
name = []
try:
with open(s,'r') as studata:
for line in studata:
try:
line = line.strip()
grade.append(int(line[0:2]))
name.append(line[3::])
except ValueError:
print("Invalid mark",line[0:2],"encountered. Skipping.")
top = topgrade(grade)
a = grade.index(top)
print("Best students:",name[a])
print("Best mark:",top)
except FileNotFoundError:
print("File not found:",s)
if __name__ == '__main__':
main()
Rather than trying to keep the students and marks in 2 separate lists (with the risk that they get out of step) it is better to use a dictionary - where the key is the mark and the value is a list of the student(s) who obtained that mark.
Then it is a simple task of just printing out the highest key, and the associated list of students. I'm using defaultdict as an easier option than having to create or append to the list for each value.
from collections import defaultdict
import sys
def main():
s = sys.argv[1]
grades = defaultdict(list)
try:
with open(s,'r') as studata:
for line in studata:
try:
line = line.strip()
grades[int(line[0:2])].append(line[3::])
except ValueError:
print("Invalid mark",line[0:2],"encountered. Skipping.")
top_mark = max(grades.keys())
print("Best students:{}".format(','.join(grades[top_mark])))
print("Best mark: {}".format(top_mark))
except FileNotFoundError:
print("File not found:",s)
if __name__ == '__main__':
main()

Resources