0% found this document useful (0 votes)
11 views10 pages

ASdfkkdkdoeoosmns PDF

Uploaded by

paulsohom777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views10 pages

ASdfkkdkdoeoosmns PDF

Uploaded by

paulsohom777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

'''

Program 32: Write the code in python to satisfy the following statements:
(i) Import the desired library to connect with database.
Note the following to establish connectivity between Python and MySQL:
• Host is localhost
• Username is root
• Password is 1234
(ii) Create a database SHGS if not available and connect with it.
(iii) Create a table if not exists in a MySQL database named EMPLOYEE.
• The details (E_CODE, E_NAME, SALARY, CITY) are the attributes of the table:
E_CODE - String
E_NAME - String
SALARY - Integer
CITY - String
(iv) Display the structure of the created table EMPLOYEE.
(v) Make changes permanently in the database.
'''

# Import the desired library


import mysql.connector

# Establishing the connection


conn = mysql.connector.connect(host = "localhost",
123 user = "root",
password = "1234")

# Check if connection was successful


if (conn):
print("Connection Established")
else:
print("Connection Not Established")

# Creating a cursor object using the cursor() method


cursor = conn.cursor()

# Preparing query to create a database


query = "CREATE DATABASE IF NOT EXISTS SHGS"
# Executing the Query to Create the database
cursor.execute(query)
print("Database Exists / Created")

# Connect and Use the database


cursor.execute("USE SHGS")

# Preparing query to create the table


query = """CREATE TABLE IF NOT EXISTS EMPLOYEE (
E_CODE VARCHAR(5) PRIMARY KEY,
E_NAME VARCHAR(25) NOT NULL,
SALARY INTEGER,
CITY VARCHAR(15) ) ;"""

# Executing the Query to Create the table


cursor.execute(query)
print("Table Exists / Created")

# Preparing query to show EMPLOYEE table structure


query = "DESC EMPLOYEE"

# Executing the Query to show EMPLOYEE table structure


cursor.execute(query)

# Fetches all rows of a query result as List of Tuples


print(cursor.fetchall())

# Commit changes to the database


conn.commit()

# Closing the connection


conn.close()
'''
Program 33: Write the code in python to satisfy the following statements:
Note the following to establish connectivity between Python and MySQL:
• Host is localhost
• Username is root
• Password is 1234
• Database is SHGS
Insert the following data in table named EMPLOYEE.
-------------------------------------------------------------------
| E_CODE | E_NAME | SALARY | CITY |
-------------------------------------------------------------------
| E002 | RAVI KUMAR | 35050 | ASANSOL |
| E005 | DINESH SINGH | 38200 | DURGAPUR |
| E008 | SAKSHI SHREE | 34250 | KULTI |
| E009 | ADITI SINHA | 40280 | DURGAPUR |
| E012 | SURESH THAKUR | 42500 | ASANSOL |
-------------------------------------------------------------------
Make changes permanently in the database.
'''

# Import the desired library


import mysql.connector

# Establishing the connection


conn = mysql.connector.connect(host = "localhost",
user = "root",
password = "1234",
database = "SHGS")

# Check if connection was successful


if (conn):
print("Connection Established")
else:
print("Connection Not Established")

# Creating a cursor object using the cursor() method


cursor = conn.cursor()

# Preparing query to insert data the database table


query = """INSERT INTO EMPLOYEE VALUES
("E002", "RAVI KUMAR", 35050, "ASANSOL"),
("E005", "DINESH SINGH", 38200, "DURGAPUR"),
("E008", "SAKSHI SHREE", 34250, "KULTI"),
("E009", "ADITI SINHA", 40280, "DURGAPUR"),
("E012", "SURESH THAKUR", 42500, "ASANSOL"); """

# Executing the Query to insert data the database table


cursor.execute(query)
print("Data inserted sucessfully")

# Commit changes permanent to the database


conn.commit()

# Closing the connection


conn.close()
'''
Program 34: Note the following to establish connectivity between Python and MySQL:
• Host is localhost
• Username is root
• Password is 1234
• Database is SHGS

Schema of table EMPLOYEE is shown below :


EMPLOYEE (E_CODE, E_NAME, SALARY, CITY)

Design a Python application to obtain a search criteria from user and then fetch
records based on that from EMPLOYEE table..
'''

# Import the desired library


import mysql.connector

# Establishing the connection


conn = mysql.connector.connect(host = "localhost",
user = "root",
password = "1234",
database = "SHGS")

# Check if connection was successful


if (conn):
print("Connection Established")
else:
print("Connection Not Established")

# Creating a cursor object using the cursor() method


cursor = conn.cursor()

try:
# Getting the search criteria from user
search_criteria = input("Enter Search Criteria : ")

# Preparing query to search data from the table


query = "SELECT * FROM EMPLOYEE WHERE {}".format(search_criteria)
# Executing the Query
cursor.execute(query)

# Fetching all matching row from the table and


# store the result in a variable as List of Tuples
result = cursor.fetchall();

if result == [] :
print ("No Result Found")

else:
# Print each tuple (row) by using a loop
for i in result:
print (i)

except:
print ("Try Again")

# Closing the connection


conn.close()
'''
Program 35: Note the following to establish connectivity between Python and MySQL:
• Host is localhost
• Username is root
• Password is 1234
• Database is SHGS

Schema of table "CUSTOMER" is shown below :


CUSTOMER (C_ID, C_NAME, PHONE, CITY) where C_ID is Customer ID and C_NAME
is Customer Name

Write a python menu-driven program to perform below operations in database:


• Insert new user data.
• Display all existing records.
• Delete specific user data.
• Update existing user information.
• Exit the program.
'''

# Import the desired library


import mysql.connector

# Establishing the connection


conn = mysql.connector.connect(host = "localhost",
user = "root",
password = "1234",
database = "SHGS")

# Check if connection was successful


if (conn):
print("Connection Established")
else:
print("Connection Not Established")

# Creating a cursor object using the cursor() method


cursor = conn.cursor()

# Create Table if not available


query = 'CREATE TABLE IF NOT EXISTS CUSTOMER (C_ID INT PRIMARY KEY, C_NAME
VARCHAR(25), PHONE VARCHAR(10), CITY VARCHAR(20))'
# Executing Query to Create Table
cursor.execute(query)

# Inserting New Data


def insert():
C_ID = int(input("Enter Customer ID : "))
C_NAME = input("Enter Customer Name : ")
PHONE = int(input("Enter 10 digit Phone Number : "))
CITY = input("Enter Customer City : ")
query = "INSERT INTO CUSTOMER VALUES ({}, '{}', '{}', '{}')".format(C_ID,
C_NAME, str(PHONE), CITY)
cursor.execute(query)
conn.commit() # Data is Parmanently Saved
print("Data Inserted Sucessfully.")

# Search Records
def search(term):
query = "SELECT * FROM CUSTOMER {}".format(term)
cursor.execute(query)
result = cursor.fetchall();
rec = cursor.rowcount
print("Record Found = ", rec, "\n")
for row in result:
print("Customer ID:", row[0])
print("Customer Name:", row[1])
print("Customer Phone:", row[2])
print("Customer City:", row[3])
print("==========================")

# Delete User Data


def delete():
C_ID = int(input("Enter the user id which you want to delete: "))
query = "SELECT * FROM CUSTOMER WHERE C_ID = {}".format(C_ID)
cursor.execute(query)
result = cursor.fetchone();
if result:
print("Customer ID:", result[0])
print("Customer Name:", result[1])
print("Customer Phone:", result[2])
print("Customer City:", result[3])
print("==========================")
query = "DELETE FROM CUSTOMER WHERE C_ID = {}".format(C_ID)
cursor.execute(query)
conn.commit() # Data is Parmanently Deleted
print("Customer ID", C_ID, "is deleted.")
else:
print("Customer ID Not Found! Please Try Again....")

# Update Existing User Data by C_ID


def update():
C_ID = int(input("Enter Existing Customer ID for Update: "))
query = "SELECT * FROM CUSTOMER WHERE C_ID = {}".format(C_ID)
cursor.execute(query)
result = cursor.fetchone();
if result:
print("Customer ID:", result[0])
print("Customer Name:", result[1])
print("Customer Phone:", result[2])
print("Customer City:", result[3])
print("==========================")
C_NAME = input("Enter Customer Name (Press Enter to Skip): ")
PHONE = input("Enter Phone Number (Press Enter to Skip): ")
CITY = input("Enter Customer City (Press Enter to Skip): ")
if C_NAME =="":
C_NAME = result[1]
if PHONE =="":
PHONE = result[2]
if CITY =="":
CITY = result[3]
query = "UPDATE CUSTOMER SET C_NAME='{}', PHONE='{}', CITY='{}' WHERE
C_ID = {}".format(C_NAME, str(int(PHONE)), CITY, C_ID)
cursor.execute(query)
conn.commit() # Data is Parmanently Saved
print("Data Updated Sucessfully.")
else:
print("Customer ID Not Found! Please Try Again....")
def main():
try:
while True:
print("\n_*_*_*_*MAIN_MENU_*_*_*_*_\n")
print("Press 1 to Insert new User Data.")
print("Press 2 to Display all Records.")
print("Press 3 to Delete Specific User Data.")
print("Press 4 to Update Exiting User Data.")
print("Press 5 to Exit the Program.")
choice = input("Enter Your Choice = ")

if (choice == '1'):
# Inserting New Data
insert()
elif choice == '2':
# Display all Records
search("")
elif choice == '3':
# Delete User Data
delete()
elif choice == '4':
# Update Existing User Data by C_ID
update()
elif choice == '5':
conn.close()
break
else:
print("Invalid Choice! Please Try Again....")
except:
print("Invalid Details! Please Try Again....")
main()
main()

You might also like