jeudi 4 février 2016

Python code simply creating databases

from sqlite3 import *

def main():

    opts = {'1': addProduct, '2': delProduct, '3': showAll,
            '4': sortPrice, '5': findPrice, '6': findType}


    if showAll() == -1:
        makeShoppingTable()

    print("*** Shopping Database ***")
    while 1:
        print("""
Please select an option.
1 - Add a new product.
2 - Delete a product.
3 - Show all products.
4 - Sort products by price.
5 - Find products by price.
6 - Find products by type.
q - Exit.""")
        choice = input("Your choice: ")
        try:
            print(opts[choice]())
        except KeyError:
            if choice == 'q':
                return
            print("Huh?")

def getNum(msg):
    """Validates integer input."""
    while 1:
        try:
            return int(input(msg))
        except ValueError:
            print("Please enter a number.")

def makeShoppingTable():
    """This creates a database with a blank table."""
    with connect("Shopping.db") as db:
        cursor = db.cursor()

        cursor.execute("""
            CREATE TABLE Product(
            ProductID integer,
            Product text,
            Type string,
            Price integer,
            Primary Key(ProductID));""")
        db.commit()

def findPrice():
    """Finds products with a certain price."""
    return find("price", getNum("Enter the price: "))

def findType():
    """Select all products of a certain type."""
    return find("type", input("Type: "))

def find(search, term):
    """Helper function for the find functions."""
    with connect("Shopping.db") as db:
        cursor = db.cursor()
        sql = "select * from products where {} = ?".format(search)
        cursor.execute(sql,(term,))
        db.commit()
        results = cursor.fetchall()
        if results:
            return pretty(results)
        else:
            return "The query returned no results."

def pretty(r):
    """Prepares the result for printing."""
    msg = "\n{0:3} {1:<15} {2:<20} {3:<4}\n".format("ID", "Product","Type", "Price")
    msg += '=' * 45 + '\n'
    msg += '\n'.join("{0:<3} {1:<15} {2:<20} {3:<4}".format(*i) for i in r)
    return msg

def delProduct():
    """Removes a product from the database."""
    with connect("Shopping.db") as db:
        cursor = db.cursor()
        sql = "delete from product where productid = ?"
        cursor.execute(sql,(getNum("Enter product ID: "),))
        db.commit()
    return "Record removed from database."  

def addProduct():
    """Adds a record to the database."""
    Product = input("Product: ")
    Type = input("Type: ")
    Price = getNum("Price: ")
    with connect("Shopping.db") as db:
        cursor = db.cursor()
        sql = "insert into Product (Product, Type, Price) values(?,?,?)"
        cursor.execute(sql,(Product, Type, Price))
        db.commit()
    return "\"{}\" added to database.".format(title)

def sortPrice():
    """Returns all the prices, sorted by Price."""
    return showAll("order by Price")

def showAll(n = ''):
    """Prints all the films in the database."""
    try:
        with connect("Shopping.db") as db:
            cursor = db.cursor()
            sql= "Select * from Shopping {}".format(n)
            cursor.execute(sql)
            r = cursor.fetchall()
            if r:
                return pretty(r)
            else:
                return "Empty database."

    except OperationalError:
        return -1

if __name__ == "__main__":
    main()

Can anyone tell me what is wrong with the code

Aucun commentaire:

Enregistrer un commentaire