Advertisement
DrAungWinHtut

mysqlfunction.py

Jul 20th, 2023
1,472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. import mysql.connector
  2.  
  3. def create_connection(host, username, password, database):
  4.     connection = mysql.connector.connect(
  5.         host=host,
  6.         user=username,
  7.         password=password,
  8.         database=database
  9.     )
  10.     return connection
  11.  
  12. def close_connection(connection):
  13.     if connection:
  14.         connection.close()
  15.  
  16. def execute_query(connection, query, values=None):
  17.     cursor = connection.cursor()
  18.     if values:
  19.         cursor.execute(query, values)
  20.     else:
  21.         cursor.execute(query)
  22.     connection.commit()
  23.     return cursor
  24.  
  25. def create_user(connection, name, email):
  26.     query = "INSERT INTO users (name, email) VALUES (%s, %s)"
  27.     values = (name, email)
  28.     execute_query(connection, query, values)
  29.  
  30. def read_users(connection):
  31.     query = "SELECT id, name, email FROM users"
  32.     result = execute_query(connection, query)
  33.     users = []
  34.     for row in result:
  35.         user = (row[0], row[1], row[2])
  36.         users.append(user)
  37.     return users
  38.  
  39. def update_user(connection, user_id, name, email):
  40.     query = "UPDATE users SET name = %s, email = %s WHERE id = %s"
  41.     values = (name, email, user_id)
  42.     execute_query(connection, query, values)
  43.  
  44. def delete_user(connection, user_id):
  45.     query = "DELETE FROM users WHERE id = %s"
  46.     values = (user_id,)
  47.     execute_query(connection, query, values)
  48.  
  49. if __name__ == "__main__":
  50.     host = "localhost"
  51.     username = "your_username"
  52.     password = "your_password"
  53.     database = "your_database_name"
  54.  
  55.     connection = create_connection(host, username, password, database)
  56.  
  57.     # Create a user
  58.     create_user(connection, "John Doe", "john.doe@example.com")
  59.  
  60.     # Read users
  61.     users = read_users(connection)
  62.     for user in users:
  63.         print(f"ID: {user[0]}, Name: {user[1]}, Email: {user[2]}")
  64.  
  65.     # Update a user
  66.     user_id_to_update = 1
  67.     update_user(connection, user_id_to_update, "Jane Smith", "jane.smith@example.com")
  68.  
  69.     # Delete a user
  70.     user_id_to_delete = 2
  71.     delete_user(connection, user_id_to_delete)
  72.  
  73.     close_connection(connection)
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement