Question

In: Computer Science

6.23 LAB: Python insert/update sqlite3 datafiles Given is a Python program that connects to a sqlite...

6.23 LAB: Python insert/update sqlite3 datafiles

Given is a Python program that connects to a sqlite database and has one table called writers with two columnns:

  • name - the name of a writer
  • num - the number of works the writer has written

The writers table originally has the following data:

name, num
Jane Austen,6
Charles Dickens,20
Ernest Hemingway,9
Jack Kerouac,22
F. Scott Fitzgerald,8
Mary Shelley,7
Charlotte Bronte,5
Mark Twain,11
Agatha Christie,73
Ian Flemming,14
J.K. Rowling,14
Stephen King,54
Oscar Wilde,1

Update the Python program to ask the user if they want to update entries or add new entries. If the name entered already exists in the writers table then the database record is updated, overwriting the original contents. If the name does not exist in the writers table, then add a new record with the writer's name and number of works. The following TODO sections must be completed.

  • Check if a writer exists in the writers table
  • If the writer exists in the table, locate an entry to be updated by writer's name and update the writer's value for num
  • If the writer does not exist in the table, add a new entry in the writers table and provide the value for name and num

Ex: If the input is:

y
J.K. Rowling
30
y
Elton John
y
62
n

The output is:

(ID, Name, Num)
(1, 'Jane Austen', 6)
(2, 'Charles Dickens', 20)
(3, 'Ernest Hemingway', 9)
(4, 'Jack Kerouac', 22)
(5, 'F. Scott Fitzgerald', 8)
(6, 'Mary Shelley', 7)
(7, 'Charlotte Bronte', 5)
(8, 'Mark Twain', 11)
(9, 'Agatha Christie', 73)
(10, 'Ian Flemming', 14)
(11, 'J.K. Rowling', 30)
(12, 'Stephen King', 54)
(13, 'Oscar Wilde', 1)
(14, 'Elton John', 62)

Solutions

Expert Solution

# import necessary module(s)
import sqlite3
from sqlite3 import Error

def connect(dbFileName):
    #  This function connects to the database
    # @Param: data base file name
    # Return: connection
    connection = None
    # connect to data base
    try:
        connnection = sqlite3.connect(dbFileName)
        # return the connection
        return connnection
    except Error as err:
        # show error
        print(err)
    # return to caller
    return connection


def createTable(connection, query):
    #  This function creates a table
    # @Param: connection and table creation query
    # Return: 

    # execute query
    try:
        c = connection.cursor()
        c.execute(query)
    # if query throws error
    except Error as e:
        print(e)


def addData(dbFileName):
    # create a database connection
    connection = connect(dbFileName)

    # enter name and number
    name=str(input("Enter the name: "))
    num=int(input("Enter a number: "))

    # create cursor
    cursor=connection.cursor()
    # execute query
    cursor.execute("SELECT Name FROM writers WHERE Name=?",(name,))
    # fetch all
    check=cursor.fetchall()
    # If writer not present insert in table
    if len(check)==0:
        connection.execute("INSERT INTO writers(Name,Num) VALUES(?,?)",(name,num))
        # show success message
        print("Data added successfully!!!")
    else:
        # if data already present update it with new
        connection.execute("UPDATE writers set Num=? where Name = ?",(num,name))
        # show success message
        print("Data was avialable and it is updated now!!!")
    # commit the changes
    connection.commit()
    # close the connection
    connection.close()

def updateData(dbFileName):
    # This function update data
    # @Param: database filename
    
    # create a database connection
    connection = connect(dbFileName)

    # enter name and number
    name=str(input("Enter the name: "))
    num=int(input("Enter a number to update: "))

    # update data
    try:
        connection.execute("UPDATE writers set Num=? where Name = ?",(num,name))
    # if query throws error
    except Error as e:
        print("Error while updating!!")

    # commit the changes
    connection.commit()
    # close the connection
    connection.close()


def showData(dbFileName):
    # This function shows all the data
    # @Param: database filename

    # create a database connection
    connection = connect(dbFileName)

    # select all from table
    dataRow = connection.execute("SELECT * FROM writers")
    print("\n(ID, Name, Num)")
    row = 1
    #  show record
    for fields in dataRow:
        print("( {0}, {1}, {2} )".format(fields[0],fields[1],fields[2]))
        row = row + 1

    # close the connection
    connection.close()
    

# main function
def main(database, query):
    # This function handles other function
    # @Param: database name ad table creation query
    
    # create a database connection
    connection = connect(database)

    # create tables
    if connection is not None:
        # call function to create table
        createTable(connection, query)
        print("Succesfully connected to database!!")
    else:
        print("Error!! Unable to connect to database!!")


    while True:
        print("\n\nEnter 1 to add data")
        print("Enter 2 to update data")
        print("Enter 3 to show data")
        print("Enter 4 exit")
        choice = int(input("Your choice >> "))
        if choice == 4:
            break
        if choice == 1:
            addData(database)
        elif choice == 2:
            updateData(database)
        elif choice == 3:
            showData(database)

# deiver code
if __name__ == '__main__':
    # intialize database name
    # and query
    database = "writers.db"

    query = """ CREATE TABLE IF NOT EXISTS writers (
                ID integer PRIMARY KEY,
                Name text,
                Num  integer
               ); """
    # call main
    main(database, query)

___________________________________________________________________

___________________________________________________________________

Succesfully connected to database!!


Enter 1 to add data
Enter 2 to update data
Enter 3 to show data
Enter 4 exit
Your choice >> 3

(ID, Name, Num)
( 1, James Bond, 23 )
( 2, Harry Potter, 20 )
( 3, J K Rowling, 25 )


Enter 1 to add data
Enter 2 to update data
Enter 3 to show data
Enter 4 exit
Your choice >> 2
Enter the name: James Bond
Enter a number to update: 50


Enter 1 to add data
Enter 2 to update data
Enter 3 to show data
Enter 4 exit
Your choice >> 3

(ID, Name, Num)
( 1, James Bond, 50 )
( 2, Harry Potter, 20 )
( 3, J K Rowling, 25 )


Enter 1 to add data
Enter 2 to update data
Enter 3 to show data
Enter 4 exit
Your choice >> 1
Enter the name: Jane Austen
Enter a number: 6
Data added successfully!!!


Enter 1 to add data
Enter 2 to update data
Enter 3 to show data
Enter 4 exit
Your choice >> 3

(ID, Name, Num)
( 1, James Bond, 50 )
( 2, Harry Potter, 20 )
( 3, J K Rowling, 25 )
( 4, Jane Austen, 6 )


Enter 1 to add data
Enter 2 to update data
Enter 3 to show data
Enter 4 exit
Your choice >> 4

___________________________________________________________________

___________________________________________________________________


Note: If you have queries or confusion regarding this question, please leave a comment. I would be happy to help you. If you find it to be useful, please upvote.


Related Solutions

6.23 LAB: Python insert/update sqlite3 datafiles Given is a Python program that connects to a sqlite...
6.23 LAB: Python insert/update sqlite3 datafiles Given is a Python program that connects to a sqlite database and has one table called writers with two columnns: name - the name of a writer num - the number of works the writer has written The writers table originally has the following data: name, num Jane Austen,6 Charles Dickens,20 Ernest Hemingway,9 Jack Kerouac,22 F. Scott Fitzgerald,8 Mary Shelley,7 Charlotte Bronte,5 Mark Twain,11 Agatha Christie,73 Ian Flemming,14 J.K. Rowling,14 Stephen King,54 Oscar Wilde,1...
In Java Please!!! 6.22 LAB: Python and sqlite basics Write a Python program that connects to...
In Java Please!!! 6.22 LAB: Python and sqlite basics Write a Python program that connects to a sqlite database. Create a table called Horses with the following fields: id (integer): a primary key and not null name (text) breed (text) height (real) birthday (text) Next, insert the following data row into the Horses table: id: 1 name: 'Babe' breed: 'Quarter Horse' height: 15.3 birthday: '2015-02-10' Output all records from the Horses table. Ex: With the above row inserted, the output...
Given is a Python program that connects to a sqlite database and has one table called...
Given is a Python program that connects to a sqlite database and has one table called writers with two columnns: name - the name of a writer num - the number of works the writer has written The writers table originally has the following data: name, num Jane Austen,6 Charles Dickens,20 Ernest Hemingway,9 Jack Kerouac,22 F. Scott Fitzgerald,8 Mary Shelley,7 Charlotte Bronte,5 Mark Twain,11 Agatha Christie,73 Ian Flemming,14 J.K. Rowling,14 Stephen King,54 Oscar Wilde,1 Update the Python program to ask...
DBMS Create/Insert/Update SQL I need the create, insert, and update SQL statement for this table as...
DBMS Create/Insert/Update SQL I need the create, insert, and update SQL statement for this table as if it were being added to MySQL (please give explanations for each line of SQL code and a copy of the code as it would be entered into the query by itself: Customer PK Customer ID Text Phone Number int name text address ID int email text FK vendor ID int Vendor is the name of the table the FK comes from.
DBMS Create/Insert/Update SQL I need the create, insert, and update SQL statement for this table: Customer...
DBMS Create/Insert/Update SQL I need the create, insert, and update SQL statement for this table: Customer PK Customer ID Text Phone Number int name text address ID int email text FK vendor ID int Vendor is the name of the table the FK comes from.
write a program in python that insert a number in the middle of an array. Assume...
write a program in python that insert a number in the middle of an array. Assume that the length of an array is even. For instance, is a=(1,4,7,9) and num=100, then really=(1,4,100,7,9)
Chapter 6: Use a list to store the players Update the program in python so that...
Chapter 6: Use a list to store the players Update the program in python so that it allows you to store the players for the starting lineup. This should include the player’s name, position, at bats, and hits. In addition, the program should calculate the player’s batting average from at bats and hits. Console ================================================================ Baseball Team Manager MENU OPTIONS 1 – Display lineup 2 – Add player 3 – Remove player 4 – Move player 5 – Edit player...
Chapter 6: Use a list to store the players In Python, Update the program so that...
Chapter 6: Use a list to store the players In Python, Update the program so that it allows you to store the players for the starting lineup. This should include the player’s name, position, at bats, and hits. In addition, the program should calculate the player’s batting average from at bats and hits. Console ================================================================ Baseball Team Manager MENU OPTIONS 1 – Display lineup 2 – Add player 3 – Remove player 4 – Move player 5 – Edit player...
PYTHON In this lab we will design a menu-based program. The program will allow users to...
PYTHON In this lab we will design a menu-based program. The program will allow users to decide if they want to convert a binary number to base 10 (decimal) or convert a decimal number to base 2 (binary). It should have four functions menu(), reverse(), base2(), and base10(). Each will be outlined in detail below. A rubric will be included at the bottom of this document. Menu() The goal of menu() is to be the function that orchestrates the flow...
8.16 LAB: Mileage tracker for a runner Given the MileageTrackerNode class, complete main() to insert nodes...
8.16 LAB: Mileage tracker for a runner Given the MileageTrackerNode class, complete main() to insert nodes into a linked list (using the InsertAfter() function). The first user-input value is the number of nodes in the linked list. Use the PrintNodeData() function to print the entire linked list. DO NOT print the dummy head node. Ex. If the input is: 3 2.2 7/2/18 3.2 7/7/18 4.5 7/16/18 the output is: 2.2, 7/2/18 3.2, 7/7/18 4.5, 7/16/18 _____________________________ The given code that...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT