Skip to main content

MySQL

MySQL

import library:

from getpass import getpass
from mysql.connector import connect, Error

Configuring MySQL connection details:

try: ##try statement used as the code isn't guaranteed to function##
    connection = mysql.connector.connect(
        host="localhost",
        user="db_user",
        password="db_pass",
        database="user_database"
     )

If you have multiple separate DB connections being made to the same DB, it would be worth defining this connection as a function, and returning the value connection so that a query can be run. for example:

Querying a MySQL database:

 

Examples
import mysql.connector
from getpass import getpass
from mysql.connector import connect, Error

##User Management Application##
print("User Management")


##User Option Selection##
def option():
  options_list = {1 : "view", 2: "delete", 3: "create"}
  option_selection = int(input("Select an option\n1. View Users\n2. Delete User\n3. Create User\n"))
  if option_selection in options_list:
    print(f"{options_list[option_selection]} users:")
else:
  print("Invalid Option")
return option_selection


option_selection = option()

##DATABASE CONNECTION AND QUERY##
def database_query(option_selection):
  if option_selection == 1:
    connection = None
    cursor = None
    try:
      print("Connecting to database...")
      # Establish a connection to the MySQL database
      connection = mysql.connector.connect(
      host="localhost",
      user="python",
      password="",
      database="user_database"
      )


if connection.is_connected():
  print("Connection Established...\nQuerying Database...")
  cursor = connection.cursor()
  query = "SELECT * FROM users"
  cursor.execute(query)
  results = cursor.fetchall()

  for row in results:
    print(row)

except Error as e:
print("Error:", e)


finally:
  if cursor is not None:
    cursor.close()
  if connection is not None and connection.is_connected():
    connection.close()
    print("Connection closed")
    return option_selection

# Run the function
database_query(option_selection)