D17 #100DaysOfCode: Databases + Python

After a couple of days of brain fog I am now on another project. This time I am creating an app that stores data into a backend database.

The data I’m storing is just based on cars, so like make, model and rego number. I then am able to search the database using my code for that rego number to see what car it’s assigned to.

For the database I am using SQLite, it’s pretty simple to setup, and I am also using DBeaver to just verify everything is working.

Below is a GIF of me adding a car, as well as using my code to pull it from the database.

code-capture

I also have a few options in the code that allows you to create a new database or use the existing one. I still have a bit to clean up, but here is the code as it sits now.

    import sqlite3
    
    class Car():
        def __init__(self, make, model, rego):
            self.make = make
            self.model = model
            self.rego = rego
        
        def description(self):
            print(f"You have entered in the following: {self.make} {self.model} with the rego {self.rego}")
    
    newCar = Car
    createDB = input("Create new Database = n | Add to existing Database = A | Select from database = S").lower()
    def main():
        if createDB == 'n':
            newDatabase()
        elif createDB == 'a':
            newCar.make = input("Please enter in the make: ")
            newCar.model = input("Please enter in the model: ")
            newCar.rego = input("Please enter in the rego: ")
            newCar.description(newCar)
            database()
        elif createDB == 's':
            selectRego = input("What rego do you want to look up?: ")
            conn = sqlite3.connect('carRego_db.sqlite')
            cur = conn.cursor()
            cur.execute(f'SELECT * FROM cars WHERE rego="{selectRego}"')
            data = cur.fetchall()
            print(data)
        else:
            print("Error!")
    
    def database():
        conn = sqlite3.connect('carRego_db.sqlite')
        cur = conn.cursor()
        cur.execute(f'INSERT INTO cars (make, model, rego) values ("{newCar.make}", "{newCar.model}", "{newCar.rego}")')
        conn.commit()
        conn.close()
    
    
    def newDatabase():
        dbname = input("What is your databse called? ")
        conn = sqlite3.connect(f'{dbname}.sqlite')
        cur = conn.cursor()
        cur.execute(f'CREATE TABLE {dbname} (make VARCHAR, model VARCHAR, rego VARCHAR PRIMARY KEY)')
    
    main()
Written on October 7, 2019