Created
August 27, 2024 02:52
-
-
Save pablohdzvizcarra/19144156ffeb27e6932cb6401a9ac625 to your computer and use it in GitHub Desktop.
Python application to perform common operations in a SQL database using the mysql.connector client library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
from mysql.connector import Error, MySQLConnection | |
def create_connection() -> MySQLConnection: | |
try: | |
connection: MySQLConnection = mysql.connector.connect( | |
host="", | |
database="example", | |
user="admin", | |
password="", | |
port=3306, | |
) | |
if connection.is_connected(): | |
print("successful connected to the database") | |
return connection | |
except Error as e: | |
print(e) | |
def create_database(conn: MySQLConnection, database_name: str): | |
print(f"Creating the database {database_name}") | |
cursor = conn.cursor() | |
cursor.execute(f"CREATE DATABASE {database_name}") | |
cursor.close() | |
def create_table(conn: MySQLConnection, table_name: str): | |
print(f"Creating the table {table_name.upper()}") | |
cursor = conn.cursor() | |
cursor.execute(f"DROP TABLE IF EXISTS {table_name.upper()}") | |
sql = f"""CREATE TABLE {table_name.upper()}( | |
NAME VARCHAR(255) NOT NULL, | |
ADDRESS VARCHAR(20) | |
)""" | |
cursor.execute(sql) | |
cursor.close() | |
def create_record(conn: MySQLConnection, table: str, name: str, address: str): | |
print("Inserting one record in the database") | |
cursor = conn.cursor() | |
sql = f"INSERT INTO {table.upper()} (NAME, ADDRESS) VALUES (%s, %s)" | |
cursor.execute(sql, [name, address]) | |
conn.commit() | |
print("Record inserted in the database") | |
def read_records(conn: MySQLConnection, table: str): | |
print(f"Getting all records from the table {table.upper()}") | |
cursor = conn.cursor() | |
sql = f"SELECT * FROM {table.upper()}" | |
cursor.execute(sql) | |
records = cursor.fetchall() | |
for record in records: | |
print(record) | |
if __name__ == "__main__": | |
connection = create_connection() | |
table_name = "customer" | |
# create_table(connection, table_name) | |
# create_record(connection, table_name, "James Gosling", "Java Father") | |
# create_record(connection, table_name, "Guido Van Roose", "Python creator") | |
read_records(connection, table_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment