In: Computer Science
Using Python, write a segment of code to populate the table "employee" of the database "EmployeeDB” with the data below. Import your choice of DB connector (import MySQLdb/sqlite3…)
Create the“employee” table with schema = [name, address, age]
Insert this employee: John Doe, 7001 E Williams Field, 32
Answer
here is your python code , if you have any doubt please comment. I am here to help you.
Here i used python3,sqlite3 and jupyter notebook as my editor.
Here is your code
import sqlite3
from sqlite3 import Error
def make_connection(db_name):
conn = None
try:
conn = sqlite3.connect(db_name)
return conn
except Error as e:
print(e)
return conn
def create_table(conn, create_table_sql):
try:
#reate a Cursor object by calling the cursor() method of the Connection object
c = conn.cursor()
#executing query
c.execute(create_table_sql)
except Error as e:
print(e)
def insert_table(conn,in_table):
sql = ''' INSERT INTO employee(name,address,age)
VALUES(?,?,?) '''
try:
#reate a Cursor object by calling the cursor() method of the Connection object
cur = conn.cursor()
#execute query with our parameters.
cur.execute(sql, in_table)
#If you don't call this method, anything you did since the last call to commit() is not visible from other database connections.
conn.commit()
except Error as e:
print(e)
def main():
#database name
database = r"EmployeeDB.db"
#created a query string for creating table employee in EmployeeDB
cr_table= """ CREATE TABLE IF NOT EXISTS employee (
name text NOT NULL,
address text,
age number
); """
#data for insert the employee table
data_1 = ('John Doe', '7001 E Williams Field', 32)
# create a database connection
conn = make_connection(database)
# create tables and insert data
if conn is not None:
create_table(conn, cr_table)
insert_table(conn,data_1)
else:
print("Error! cannot create the database connection.")
if __name__ == '__main__':
main()
output
Providing here jupyter notebook screenshot,because you may meet any indentation error refer this image too
Any doubt please comment
Thanks in advance