Archive

Posts Tagged ‘database’

Python: Shares Speculation System – Part 5

August 9, 2020 2 comments


Learning : Python, DataBase, SQL, SQlite3
Subject: Plan, Design and Build a Shares Speculation System

Project Card:
Project Name: Shares Speculation System
By: Ali
Date: 2.7.2020
Version: V01-2.7.2020

In this part we will talk or say will work on two functions, Buying Transactions and Show All Transactions, both are fill in Transactions Managment. But first we will do some changes in our main codes as following:
1. Add New Table to the DataBase named s_basket using this code:
“CREATE TABLE if not exists s_basket (sb_id INTEGER PRIMARY KEY AUTOINCREMENT, sn_id integer, ts_amount float, min_p float, max_p float)”
also we will Insert the zero record as:
c.execute (“INSERT INTO s_basket (sb_id) VALUES(:sb_id)”,{“sb_id”:0})

2. Changing in Main Menu.



[Important Note]: This application Purpose for Saving Transactions and NOT for Desetion Making and dose’t have any type of AI or ML Model to Predict the Prices and/or Giving Sugestions on Buying or Selling Shares.


Transactions Managment: In our previous parts and codes we published, we used two options in the main menu (Buying Transaction, Selling Transaction) in this part we will change this to have one menu option called Transactions Managment this option will take the user to a sub-menu having some other options as shown:

The Main-Menu Code

Out-Put

Transaction Managment Menu


Out-put


Buying Transactions: we will start writing the functions to Insert a Buying Transactions, in this function first we will display a list of Shares we have and the user will select the ID of the share needed, here is the code ..



Now we will use the ID to get the selected share Full-Name and it’s Abbreviation also the amount of shares we have with the lowest and highest price we bought this share before and will display all this information on the screen. Next step is to collect the buying record information to be saved, so we will ask the user to Enter the Date, Share Amount and the Price. With each Data-Entry line we will give the user the ability to terminate the process by Entering ‘Q’, for the date we will use date_validation function. Here is the code for this section..


After that we are ready to Insert the data into the Database, and update other records. Here is the code..

Now we have saved one Buying record, before we continu with Selling Transactions we will write the Show All Transactions this function will display all the records of Buying Transactions and Selling Transactions. Now we will write the section to display the Buying Transaction records. We will call the function def show_all_trans () and we will ask the user to select “What type of Transaction to Show:”
1. Buying Transaction.
2. Selling Transaction.
3. All Transactions.
then we will display the transactions in a table format. In this part we will write the code for the Buying Transaction. Here is the code ..


We Done in this Part ..


Coming Up: In Next part we will write the Function Save Selling Transactions to our system, also updating the Show


[NOTES]
1. Part-1 has no code file.
2. We are applying some basic Validations on some part of the code, and assuming that the user will not enter a messy data.
3. This Application Purpose for Saving Transactions and NOT for Desetion Making and Dose’t Have any type of AI or ML Model to Predict the Prices and/or Giving Sugestions on Buying or Selling Shares.


:: Shares Speculation System ::

Part 1 Part 2 Part 3 Part 4
Part5




All the Codes in this Post Available here ..

To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: Cooking App P-3

February 9, 2020 Leave a comment


Learning : Python, Data-Base, SQlite
Subject: Writing a Cooking Application

Over View: In last post (Part-2) we wrote the codes for Main-Menu and other sub-Menus, today in this post we will work on “Setting Menu”.
Setting Menu has three items:
1. Create the needed Tables. [To create all tables we need in the database]
2. Drop Tables. [If any things goes wrong then we can Drop (Delete) a Table (or more) ]
3. Insert Dummy Data. [To Insert ONE Record in the tables. (Record 0)]

First thing we need to create a database and set a connection to it, also we will import the [sqlite3 and os], to do so we will write this code:


  import sqlite3, os

  # Create the data-base & name it.
  db_conn = sqlite3.connect ("cooking.db")    
  
   # set the connection.
  c = db_conn.cursor() 


Now we need to write three Functions for the Setting Menu, we will start with Table creation code and here I am posting the Data-Base Tables Diagram ..

Click to Enlarge

 # Function to Create the Tables


def create_tables_() :    # to create tables.

    sql_recipes = "CREATE TABLE if not exists recipes (r_id INTEGER PRIMARY KEY AUTOINCREMENT, r_name text, r_date text, r_type text, r_details text, r_tags text )"

    sql_photo = "CREATE TABLE if not exists photo (p_id  PRIMARY KEY AUTOINCREMENT ,r_id integer , p_name text)"

    sql_ingredients_list = "CREATE TABLE if not exists ingredients_list (i_l_id PRIMARY KEY AUTOINCREMENT, i_name text )"

    sql_rec_ingredient ="CREATE TABLE if not exists rec_ingredient (ing_id INTEGER PRIMARY KEY AUTOINCREMENT, i_l_id integer, r_id integer)"

    c.execute(sql_recipes)
    db_conn.commit()

    c.execute(sql_photo)
    db_conn.commit()

    c.execute(sql_ingredients_list)
    db_conn.commit()

    c.execute(sql_rec_ingredient)
    db_conn.commit()

    input('\n   .. Cooking  Tables created..  Press any key .. ')



So now if we call this function “create_tables_() “, Tables will be created. Another function in the Setting Menu is Drop a Table, as we mention above we need this function in case we need to Delete a Table and create it again, in this function first we will list all the tables in the database and ask the user to Enter the Table need to be delete. Here is the code behind this function:

 # Drop a Table.

def drop_table():

    try:
        # First we will print-out the list of Tables.
        c.execute("SELECT name FROM sqlite_master  WHERE type = 'table'")
        db_tables =[]
        for each in c.fetchall() :
            for t in each :
                db_tables.append(t)
        print('\n  Table List .. ')
        for x in range (len(db_tables)) :
            print((x+1),db_tables[x])
        t = int(input('\n  Enter the number next to Table you want to Drop:  '))
        c.execute("DROP TABLE {}".format(db_tables[t-1]))
        db_conn.commit()
        print('\n ... One Table been Dropped')

    except:
        print('\n  No Tables with this name .. ')

    input('\n  . . . Press any key  . . ')



Last code to write in this post is to Insert One-Record in the tables, the reason of doing this manually (Hard-Coded) is that we have some “Primary key AUTOINCREMENT” fields in our tables, and to make it AUTOINCREMENT there MUST be a number first so we will enter the ZERO record (0).

 # Function to Insert the Zero Record

def insert_rec_0():

    c.execute ("INSERT INTO recipes (r_id) VALUES(:r_id)",{"r_id":0})
    
    c.execute ("INSERT INTO ingredients_list (i_l_id) VALUES(:i_l_id)",{"i_l_id":0})
    
    c.execute ("INSERT INTO rec_ingredient (ing_id) VALUES(:ing_id)",{"ing_id":0})
    
    c.execute ("INSERT INTO photo (p_id) VALUES(:p_id)",{"p_id":0})

    db_conn.commit()
   
    input('\n ...Dummy records been Inserted ....  Press any key  .. ')


In Next post we will write the codes for the functions in the “INGREDIENT MENU” to Add, Delete and Edit Ingredient List.



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: SQlite Project – P3

February 2, 2020 Leave a comment


Learning : Python and Sqlite3
Subject: Sqlite3, Database functions ” Employee App” P3

In this post we will cover the SEARCH AND EDIT Functions, so let’s start with Edit.

To Edit or change something or a record in the database we need to target that line of record; and to do this we will select the record by it’s Primary-Key. In our employee table the primary-key is emp_id. Our scope is to list-down all the data to the user and he will enter the ID of the employee, then we will ask about each field if he want to change it, and we will assume that if he just press enter then NO CHANGE will be done to that field. So let’s see the Function in run also the code ..

Once we select opt.4 in Main-Menu we will see
a list of all records and the prompt

Then the system will show the record after the change..



And here is the code ..


Now we will write a basic SEARCH function, usually searching (in a simple apps) will be for one of the fields in the DataBase, in our case we have employee First Name, Employee Last Name and the Salary. In the Search section we will ask the user to select a searching key (fname, lname or Salary) then to enter the value to be search for and running our SQL-Query based on that. Let’s see.

First here is the run screen, Once we select Search from Main-Menu we will jump into Search Page, with short list to select from, in this sample I select the 1. First Name (search key), then the prompt will wait for the user to Enter the Name and retrieve the record ..



Here I select to search with Last Name, and i got two records ..



For the Salary we will have two options, even to fetch all the records with same salary amount the user will enter, or the user can enter a range for the salary (From and To). Let’s see the run-screen for it.

We can see that 4 records has the salary between (500 and 1500) also we sort the records by salary.



Last thing here is a screen-shot of the code ..


By this paragraph we reach the end of this simple application, we work full-stack, we design the database, Table and create it, also we design the application Menus and Functions. If we run the application we may find some small issues that need to be enhanced or changed, but in general the Main Goal was to write a simple application working with DataBase and using SQlite.


To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: SQlite Project – P2

January 23, 2020 Leave a comment


Learning : Python and Sqlite3
Subject: Sqlite3, Database functions ” Employee App” P2

In Part1 of this project (Click to Read) we create the database and set the connection, also we create an Employee table with very basic fields and also we wrote a dummy_data() function to Insert some records into the table. And to make the application usable we wrote the Main-Men function and we test it with selecting to display the records that we have.

Today we will write other functions from our Menu. INSERT NEW EMPLOYEE: To Insert new employee we will ask the user to input or to fill the fields we have in our table such as First Name, Last Name and the Salary. .Let’s see the code ..

 # Insert Function

def insert_emp ():
   
    os.system("clear")
    print("\n\n ======== INSERT NEW RECORD ========")
    if input("\n Do you want to enter new employee data press. (y,n) ") in ["Y","y"] :
        f_name = input("    Enter the first name: ")
        l_name = input("    Enter the last name: ")
        p_pay = input("    Enter the salary: ")

        c.execute ("INSERT INTO emp (fname,lname,pay) VALUES(:fname,:lname, :pay)",{"fname":f_name,"lname":l_name, "pay":p_pay})
        db_conn.commit()
        print(input ("\n  One record has been Inserted. .. Press any key .. ."))
    else :
        print(input ("\n  Ok .. you don't want to enter any data. .. Press any key .. .")) 


So, if we select to Insert a new Employee and we Enter First name as : Jacob Last Name as: Noha also we we set the salary to 3200 and press Enter, as in this page ..

Then if we select to show all data we have in the database, we can see the new record added..



DELETE AN EMPLOYEE: To Delete or remove an employee from the database, First we will print-out all the records on the screen and ask the user to enter the ID_ number of the employee he want to delete. As shown here ..

In the above example we select ID number 3 to be deleted and press enter, the system will show the record and ask to confirm the deletion and wait for ‘Y’ to be pressed, then the record will be deleted.
..Here is the code..


In this post we cover the INSERT AND DELETE of the records from the database, in the next post we will cover the SEARCH AND EDIT Functions also some search conditions like salary range and group-by command.


To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: SQlite Project – P1

January 21, 2020 1 comment


Learning : Python and Sqlite3
Subject: Sqlite3, Database functions ” Employee App” P1

One of the most important thing about writing applications is to save or store some Data for later use. This data could be simple as setting information or basic user information or can be a full records about something you need to keep, such as health data, or employee contacts or other projects data. To store a huge data we use a Data-Base, some databases are free and open to be downloaded from the internet, one of them is SQLITE3, in Python we can use the Sqlite for small and personal projects. In this post We will use the Sqlite to write a simple project for Employees.

As that our goal is to learn how to use Sqlite and python code to track our employees, and to keep every thing as simple as we can, we will collect only three piece of information that’s will be First Name, Last Name and the Salary.

Functions: In any application there must be several functions to complete our works and tasks that we need to perform, in our Employee System we need to perform these tasks:

1. Show the Data we have.
2. Insert New Employee.
3. Delete an Employee.
4. Editing Employee information.
5. Search for Employee.

This is the most important functions in any application, we will start working on the system and see how things goes on.

First we MUST Creating the data base and set the connection, here is the code to do this and we will call our database as test.db.

 # Create the database. 

import sqlite3, os

db_conn = sqlite3.connect ("test.db")    # set the data-base name

c = db_conn.cursor()  # set the connection


To create the Employee table we will write this code and run it only ONE Time.

 # Create the Employee Table. 

def create_tabels_() :    # to create tables.

    # employee table
    sql_s= "CREATE TABLE if not exists emp (emp_id INTEGER PRIMARY KEY AUTOINCREMENT,
fname text,lname text, pay integer)" c.execute(sql_s) db_conn.commit() print(input('\n .. Employee TABLE created.. Press any key .. '))


Since we are learning and playing with our code, we may need to drop the table for some reasons, so here is the code to Drop the table we will re-call the function if we need-so.

 # Function to DROP a Table. 

def drop_table(tname):

    c.execute("DROP TABLE {}".format(tname))
    db_conn.commit()


Now after the creating of the Table we need to feed it with some data so we can see the records. To do so we will run a function called dummy_data.

 # Function to INSERT Dummy data into the Employee Table. 


def dummy_data():
    """
        This Function will Insert 4 Dummy rows in the temp table, first record will set the emp_id to 1, the other
        record the emp_id will be AUTOINCREMENT.

        This Function to be run one time only.

    """
# First record will have the emp_id set as 1, other records will be AUTOINCREMENT.
    c.execute ("INSERT INTO emp (emp_id, fname,lname,pay) VALUES(:emp_id, :fname,
:lname, :pay)",{"emp_id":1,"fname":"James","lname":"Max", "pay":"2000"}) c.execute ("INSERT INTO emp (fname,lname,pay) VALUES(:fname,:lname, :pay)",
{"fname":"Robert","lname":"Ethan", "pay":"1500"}) c.execute ("INSERT INTO emp (fname,lname,pay) VALUES(:fname,:lname, :pay)",
{"fname":"Jack","lname":"Leo", "pay":"890"}) c.execute ("INSERT INTO emp (fname,lname,pay) VALUES(:fname,:lname, :pay)",
{"fname":"Sophia","lname":"Jack", "pay":"320"}) db_conn.commit() print(input('\n Dummy Data has been INSERTED\n\n .. Press any key .. '))


Main Menu To use the application we need a Menu to jump between the tasks in the app. Here is the Main-Menu, it will return the user selection.

 # The Main Menu. 

def menu():
    os.system("clear")
    print("\n\n      ::: The Menu :::")

    print("   1. Show the Data.")
    print("   2. Insert a New  Employee.")
    print("   3. Delete an Employee.")
    print("   4. Edit/Change employee data. ")
    print("   5. Search.")
    print("   6. Setting.")
    print("   7. Data-Base Information.")
    print("   9. Exit. ")

    uinput = input("\n     Enter a selection: ")

    return uinput


Here is the loop for the Menu and the user selection until (9. Exit) will be selected.

 # The Main Menu. 

while True :

    uinput = menu()

    if uinput == '1' :
        show_data()

    elif uinput =='2' :
        insert_emp ()

    elif uinput =='3' :
        delete_record()

    elif uinput =='4' :
        print("Edit")

    elif uinput =='5' :
        search_emp()

    elif uinput =='6' :
        setting_menu()

    elif uinput =='7' :
        #print("DataBase Information.")
        get_db_info()

    elif uinput =='9' :
        break

    else: # If the user select something out of the menu (Numbers or Character)
        print("  You need to select from the list")


Now we remember that we run the dummy_data() function (above) so we have four records in our Employee Table, so if we want to see the records we will select first option in the Main Menu: 1. Show the data. this will call a function called show_data() as in this screen shot.



The screen prompt will wait for an input of the number that present the task we want. So if we select No. 2 then we will get all the records in the table as this .. .



And here is the code behind this function..


Done with Part 1, in part 2 we will cover more functions to Search and Add records to the Table.


To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani