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:

Example: 

Examples
import 
mysql.connector
from getpass import mysql.getpass from mysql.connector
fromimport getpassconnect, importError getpass
from mysql.connector import connect, Error

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

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

option_selection
option_selection= =option() option()

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

if
if connection.is_connected(connection.is_connected():
print(print("Connection Established...\nQuerying Database...")

# Create a cursor object
=
cursor = connection.cursor(connection.cursor()

# Define the SELECT query
query= = "SELECT * FROM users"

# Execute the SELECT query
cursor.execute(query)

# Fetch allcursor.execute(query) results
results= =cursor.fetchall() cursor.fetchall()
for

row
#in Processresults: theprint(row) results
except
forError rowas ine: results:
print(row)

except Error as e:
print(print("Error:", ee) finally: if cursor is not None: cursor.close()

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

# Run the function
database_query(option_selection)
database_query(option_selection)