Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pymysql
- # Function to create a connection to the database
- def connect_to_database(db_name):
- try:
- conn = pymysql.connect(host='localhost',
- user='root',
- password='',
- database=db_name)
- print("Connected to the database successfully")
- return conn
- except Exception as e:
- print("Error connecting to the database: ", e)
- # Function to create a new table for the address book
- def create_table(conn):
- try:
- cursor = conn.cursor()
- cursor.execute("CREATE TABLE IF NOT EXISTS contacts (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), phone VARCHAR(255))")
- conn.commit()
- print("Table created successfully")
- except Exception as e:
- conn.rollback()
- print("Error creating table: ", e)
- # Function to insert a new contact into the address book
- def add_contact(conn, name, email, phone):
- try:
- cursor = conn.cursor()
- cursor.execute("INSERT INTO contacts (name, email, phone) VALUES (%s, %s, %s)", (name, email, phone))
- conn.commit()
- print("Contact added successfully")
- except Exception as e:
- conn.rollback()
- print("Error adding contact: ", e)
- # Function to view all contacts in the address book
- def view_contacts(conn):
- try:
- cursor = conn.cursor()
- cursor.execute("SELECT * FROM contacts")
- result = cursor.fetchall()
- print("Contacts:")
- for row in result:
- print(row)
- except Exception as e:
- conn.rollback()
- print("Error viewing contacts: ", e)
- # Function to delete a contact from the address book
- def delete_contact(conn, id):
- try:
- cursor = conn.cursor()
- cursor.execute("DELETE FROM contacts WHERE id=%s", (id,))
- conn.commit()
- print("Contact deleted successfully")
- except Exception as e:
- conn.rollback()
- print("Error deleting contact: ", e)
- # Connect to the database
- conn = connect_to_database("addressbook")
- # Create the contacts table if it does not already exist
- create_table(conn)
- # Prompt the user to add, view, or delete contacts
- while True:
- print("Enter 'add' to add a new contact")
- print("Enter 'view' to view all contacts")
- print("Enter 'delete' to delete a contact")
- print("Enter 'quit' to exit")
- choice = input("Choice: ")
- if choice == 'add':
- name = input("Enter name: ")
- email = input("Enter email: ")
- phone = input("Enter phone: ")
- add_contact(conn, name, email, phone)
- elif choice == 'view':
- view_contacts(conn)
- elif choice == 'delete':
- id = input("Enter ID of contact to delete: ")
- delete_contact(conn, id)
- elif choice == 'quit':
- break
- else:
- print("Invalid choice")
- # Close the connection to the database
- conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement