Page Content

Tutorials

How to create a MySQL database in Python? With code example

MySQL database in Python

MySQL, an open-source RDBMS, is quick and trustworthy. The open-source LAMP (Linux, Apache, MySQL, PHP) project relies on it. The Swedish-created MySQL is now developed, distributed, and maintained by Oracle Corporation. C and C++ are used.

MySQL’s speed, stability, and simplicity make it popular. It supports 50 million rows or more in a table and has a default file size limit of 4GB that can be raised to 8 million terabytes, making it excellent for both small and large applications. Advanced features include data security, on-demand scalability, transactional support, and 24/7 uptime.

MySQL and Python Database Interaction

A Database Management System (DBMS) is needed to develop and maintain a computer database. MySQL uses tables, which are like spreadsheets with rows and columns. MySQL is primarily accessed using SQL. Other programming languages, such as Python, can connect to and modify MySQL databases. PHP is a prominent web development language.

Connecting a Python script to MySQL requires a database connection. The server address, username, and password are usually required. Safe systems employ usernames and passwords. You can choose a database after connecting.

MySQL Database Operations

Categories of SQL commands:

  • Data Definition Language (DDL): DDL creates, modifies, and deletes database objects like tables. Create database, drop database, create table, alter table, and drop table.
  • Data Manipulation Language (DML): Inserts, deletes, updates, and retrieves table records. Select, insert, update, and delete.

Python-MySQL Database Code Example

This example demonstrates common DDL and DML operations using a conceptual Python-MySQL interaction pattern. Assume mydb_connection is an established connection object and mydb_cursor is a cursor object used to execute SQL queries.

# --- Conceptual Python-MySQL Interaction Example ---
# 1. Establish a Connection (Conceptual)
# In a real Python application, you would import a MySQL connector library
# (e.g., 'mysql.connector' or 'PyMySQL') and establish a connection.
# For example:
# import mysql.connector
# mydb_connection = mysql.connector.connect(
#   host="localhost",
#   user="your_username",
#   password="your_password"
# )
# mydb_cursor = mydb_connection.cursor()
print("1. Connected to MySQL server (conceptually).")
# 2. Create a Database
# SQL: CREATE DATABASE IF NOT EXISTS mypythondb; 
try:
    # mydb_cursor.execute("CREATE DATABASE IF NOT EXISTS mypythondb")
    print("2. Database 'mypythondb' created or already exists.")
except Exception as e:
    print(f"Error creating database: {e}")
# 3. Select the Database
# SQL: USE mypythondb; 
try:
    # mydb_cursor.execute("USE mypythondb") # Or specify db in connection
    print("3. Switched to 'mypythondb' database.")
except Exception as e:
    print(f"Error selecting database: {e}")
# 4. Create a Table
# SQL: CREATE TABLE IF NOT EXISTS students (
#      id INT AUTO_INCREMENT PRIMARY KEY,
#      name VARCHAR(100) NOT NULL,
#      age INT
# ); 
try:
    create_table_query = """
    CREATE TABLE IF NOT EXISTS students (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        age INT
    );
    """
    # mydb_cursor.execute(create_table_query)
    # mydb_connection.commit() # Commit DDL changes for some engines/modes
    print("4. Table 'students' created or already exists.")
except Exception as e:
    print(f"Error creating table: {e}")
# 5. Insert Data
# SQL: INSERT INTO students (name, age) VALUES ('Alice', 20), ('Bob', 22); 
try:
    insert_query = "INSERT INTO students (name, age) VALUES (%s, %s)"
    data = [('Alice', 20), ('Bob', 22), ('Charlie', 21)]
    # mydb_cursor.executemany(insert_query, data)
    # mydb_connection.commit()
    print("5. Data inserted into 'students' table.")
except Exception as e:
    print(f"Error inserting data: {e}")
# 6. Select Data
# SQL: SELECT * FROM students; 
try:
    # mydb_cursor.execute("SELECT * FROM students")
    # records = mydb_cursor.fetchall()
    print("\n6. Retrieving data from 'students' table:")
    # for row in records:
    #     print(row)
    # Example output: (1, 'Alice', 20)
    #                 (2, 'Bob', 22)
    #                 (3, 'Charlie', 21)
except Exception as e:
    print(f"Error selecting data: {e}")
# 7. Update Data
# SQL: UPDATE students SET age = 21 WHERE name = 'Alice'; 
try:
    update_query = "UPDATE students SET age = %s WHERE name = %s"
    # mydb_cursor.execute(update_query, (21, 'Alice'))
    # mydb_connection.commit()
    print("\n7. Updated data for 'Alice'.")
except Exception as e:
    print(f"Error updating data: {e}")
# 8. Delete Data
# SQL: DELETE FROM students WHERE name = 'Bob'; 
try:
    delete_query = "DELETE FROM students WHERE name = %s"
    # mydb_cursor.execute(delete_query, ('Bob',))
    # mydb_connection.commit()
    print("8. Deleted data for 'Bob'.")
except Exception as e:
    print(f"Error deleting data: {e}")
# 9. Close Connection (Conceptual)
# In a real Python application, you would close the cursor and connection.
# For example:
# mydb_cursor.close()
# mydb_connection.close()
print("\n9. Connection closed (conceptually).")

Code Explanation

Connection: First, connect to MySQL. The server’s hostname (e.g., “localhost”), username, and password are usually needed.

Creating a Database: The MySQL server’s CREATE DATABASE DDL command creates a new database. If the database exists, use IF NOT EXISTS to avoid problems.

Selecting a Database: MySQL’s USE command selects a database for future operations.

Creating a Table: CREATE TABLE DDL defines a table’s structure, including column names, data types (e.g., INT for integers, VARCHAR for variable-length strings), and constraints like PRIMARY KEY and NOT NULL.

Inserting Data: The INSERT INTO DML command adds rows to a table. String and date values need single or double quotations.

Selecting Data: Data retrieval relies on the SELECT DML command. SELECT column1, column2 retrieves specified columns, while SELECT * retrieves all. A WHERE clause filters records by conditions.

Updating Data: The UPDATE DML command updates table records. Usually used with a SET clause to define new values and a WHERE clause to update records. It would update all table records without a WHERE clause.

Deleting Data: DELETE FROM DML deletes table records. Similar to UPDATE, a WHERE clause is needed to remove specific rows; removing it deletes all entries.

Closing Connection: To free resources, disconnect the database connection after all operations.

Important Considerations

Error Handling: Connection failures and erroneous SQL queries can occur during database operations, therefore error handling (e.g., utilising try-except blocks in Python) is essential. Use mysql_error() to get specific error messages.

Security (SQL Injection): SQL injection vulnerabilities can result from entering dynamic data like user input directly into SQL queries. SQL injection protection is essential for online application security, and MySQL supports prepared statements.

Data Types: The right MySQL data type for each column optimises database performance and storage. MySQL supports integer, string, and date/time data types. We must accurately map Python data types to MySQL ones.

Python and MySQL Database Interaction (Context for 2010)

Computer databases require a Database Management System (DBMS). MySQL stores data in rows and columns in tables, like spreadsheets. SQL dominates MySQL database engine interaction. PHP is a popular web development language that works with MySQL, but Python can also connect to and handle MySQL databases.

The sources mention a MySQL “PYTHON Driver”. Python programs can use MySQLdb.connect to make SSL connections. MySQLdb was a popular Python MySQL driver in 2010.

Connections are needed to link Python scripts to MySQL databases. Connection parameters like the server address (‘localhost’), username (‘root’ or ‘guest’), and password are usually required. Secure systems employ usernames and passwords during authentication. Use database_name to pick a database after connecting.

Database MySQL Operations

SQL commands have numerous types:

Data Definition Language (DDL): Used to create, modify, and delete tables, views, and indexes. ALTER TABLE, CREATE TABLE, and DROP TABLE are examples.

Data Manipulation Language (DML): Used to insert, remove, update, and retrieve table records. Select, INSERT, UPDATE, and DELETE.

Data Control Language (DCL): DCL manipulates permissions and access privileges like GRANT and REVOKE.

Conceptual Python-MySQL Code Example

While the sources don’t provide a full Python script for CRUD operations, the following conceptual example demonstrates how a Python script would interact with a MySQL database using the SQL commands discussed in the sources. In a real-world scenario, you would use a specific Python MySQL driver (like MySQLdb, mysql-connector-python, or PyMySQL) to implement the connect(), cursor(), execute(), fetchall(), and commit() methods.

# --- Conceptual Python-MySQL Interaction Example ---
# Note: This code is conceptual. In a real application, you would install and import
# a specific Python MySQL driver (e.g., 'MySQLdb' or 'mysql.connector').
# The specific methods for connection and cursor might vary slightly by driver.
try:
    # 1. Establish a Connection (Conceptual Representation)
    # This represents 'mysql_connect' or similar functionality
    # from a Python driver like MySQLdb.
    # In practice:
    # import MySQLdb
    # mydb_connection = MySQLdb.connect(host="localhost", user="your_username", passwd="your_password", database="mypythondb")
    # mydb_cursor = mydb_connection.cursor()
    print("1. Connected to MySQL server (conceptually).")
    # 2. Create a Database (DDL)
    # SQL: CREATE DATABASE IF NOT EXISTS mypythondb;
    # mydb_cursor.execute("CREATE DATABASE IF NOT EXISTS mypythondb")
    # print("2. Database 'mypythondb' created or already exists.")
    # (In many setups, you would select the database directly in the connection string or via a 'USE' command)
    # 3. Create a Table (DDL)
    # SQL: CREATE TABLE IF NOT EXISTS students (
    #      id INT AUTO_INCREMENT PRIMARY KEY,
    #      name VARCHAR(100) NOT NULL,
    #      age INT
    # );
    create_table_query = """
    CREATE TABLE IF NOT EXISTS students (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        age INT
    );
    """
    # mydb_cursor.execute(create_table_query)
    # mydb_connection.commit() # DDL commands sometimes require commit depending on driver/server config
    print("3. Table 'students' created or already exists.")
    # 4. Insert Data (DML)
    # SQL: INSERT INTO students (name, age) VALUES ('Alice', 20), ('Bob', 22);
    insert_query = "INSERT INTO students (name, age) VALUES (%s, %s)"
    data_to_insert = [('Alice', 20), ('Bob', 22), ('Charlie', 21)]
    # mydb_cursor.executemany(insert_query, data_to_insert)
    # mydb_connection.commit()
    print("4. Data inserted into 'students' table.")
    # 5. Select Data (DML)
    # SQL: SELECT * FROM students;
    # mydb_cursor.execute("SELECT * FROM students")
    # records = mydb_cursor.fetchall()
    print("\n5. Retrieving data from 'students' table:")
    # for row in records:
    #     print(row)
    # Example output if data was retrieved:
    # (1, 'Alice', 20)
    # (2, 'Bob', 22)
    # (3, 'Charlie', 21)
    # 6. Update Data (DML)
    # SQL: UPDATE students SET age = 21 WHERE name = 'Alice';
    update_query = "UPDATE students SET age = %s WHERE name = %s"
    # mydb_cursor.execute(update_query, (21, 'Alice'))
    # mydb_connection.commit()
    print("\n6. Updated data for 'Alice'.")
    # 7. Delete Data (DML)
    # SQL: DELETE FROM students WHERE name = 'Bob';
    delete_query = "DELETE FROM students WHERE name = %s"
    # mydb_cursor.execute(delete_query, ('Bob',))
    # mydb_connection.commit()
    print("7. Deleted data for 'Bob'.")
except Exception as e:
    print(f"An error occurred: {e}")
    # In a real scenario, you might also want to:
    # mydb_connection.rollback() # Rollback changes on error
finally:
    # 8. Close Connection (Conceptual Representation)
    # In practice:
    # if 'mydb_cursor' in locals() and mydb_cursor:
    #     mydb_cursor.close()
    # if 'mydb_connection' in locals() and mydb_connection:
    #     mydb_connection.close()
    print("\n8. Connection closed (conceptually).")

Important Considerations

Error Handling: Python try-except blocks are essential for handling connection failures and incorrect SQL queries. Specific error messages can be returned by mysql_error().

Security (SQL Injection): Dynamic data explicitly inserted in SQL queries might cause SQL injection issues. Prepared Statements, a MySQL feature, defend web applications against such attacks.

Data Types: Database optimisation and effective storage depend on choosing the right MySQL data type (INT, VARCHAR, DATE) for each column. Numeric, text, and date/time data types are supported by MySQL. Python and MySQL data types must be mapped correctly.

Index