Skip to main content

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. As an example:

def db_connection():
    try: ##try statement used as the code isn't guaranteed to function##
        print("Connecting to database...")

        ##Database Connection##
        connection = mysql.connector.connect( ##set mysql connection details as variable connection, and initiate connection##
            host="localhost",
            user="python",
            password="",
            database="user_database"
        )
        if connection.is_connected():
            return connection
    except Error as e:
        print("Error connecting to database:", e)
        return None

@app.route('/view_users')
def view_users(): #define function database_query, pass in variable option_selection
        
        try: ##try statement used as the code isn't guaranteed to function##

            print("Connecting to database...")
            connection = db_connection()

            if connection.is_connected(): ##Validate that connection has been succesful and initiate IF
                print("Connection Established...\nQuerying Database...")
                cursor = connection.cursor()
                query = "SELECT * FROM users"
                cursor.execute(query)
                results = cursor.fetchall()
                cursor.close()
                connection.close()
                return render_template('view_users.html', users=results)
                print("Connection closed")
                for row in results:
                    print(row)

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

In this example, the value connection is returned as the output of the function, and can then be referenced later on to connect to 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)