Interacting with MySQL Databases in Python Using PyMySQL
After installing the database engine and updating the system path, configure the MySQL service to start manually. This prevents background processes from consuming memory and CPU cycles when the server is idle. Open the Windows Services manager (services.msc), locate the MySQL80 entry, access its properties, and change the startup type to Manual.
Environment Preparation
Direct communication between Python and MySQL requires the PyMySQL driver. Install the package via the terminal:
pip install pymysql
Connection Initialization
Establish a network session by instantiating a connection object. This object manages authentication and socket parameters. Execute commands and process result sets through a derived cursor instance. Cursors maintain the execution context and handle data buffering.
import pymysql
db_session = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='SecurePass123!'
)
query_engine = db_session.cursor()
query_engine.execute('SELECT VERSION()')
print(query_engine.fetchone())
db_session.select_db('test_schema')
query_engine.execute('CREATE TABLE IF NOT EXISTS sample_records (record_id INT)')
query_engine.close()
db_session.close()
To bypass explicit schema selection when targeting a single database, specify the database argument during connection setup:
import pymysql
db_handle = pymysql.connect(
host='127.0.0.1',
port=3306,
user='admin_user',
passwd='AdminPass456',
database='target_db'
)
Schema Administration
Standard procedures for managing database namespaces include creation, enumeration, deletion, and context verification.
Namespace Creation
import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='password')
cur = conn.cursor()
cur.execute('CREATE DATABASE IF NOT EXISTS analytics_db')
cur.close()
conn.close()
Namespace Enumeration
import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='password')
cur = conn.cursor()
cur.execute('SHOW DATABASES')
for schema_tuple in cur.fetchall():
print(schema_tuple[0])
cur.close()
conn.close()
Namespace Removal
import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='password')
cur = conn.cursor()
cur.execute('DROP DATABASE IF EXISTS analytics_db')
cur.close()
conn.close()
Context Verification
import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='password')
cur = conn.cursor()
conn.select_db('production_db')
cur.execute('SELECT DATABASE()')
active_schema = cur.fetchone()
print(f'Currently using: {active_schema[0]}')
cur.close()
conn.close()
Relational Structure Management
When defining tables, wrap identifiers in backticks to prevent syntax collisions with reserved words.
Table Definition
import pymysql
client = pymysql.connect(
host='localhost',
user='root',
passwd='password',
autocommit=True
)
executor = client.cursor()
client.select_db('production_db')
ddl = '''
CREATE TABLE IF NOT EXISTS `user_profiles` (
`uid` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) DEFAULT NULL,
`age` TINYINT UNSIGNED DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
'''
executor.execute(ddl)
executor.close()
client.close()
Table Deletion
import pymysql
client = pymysql.connect(host='localhost', user='root', passwd='password')
executor = client.cursor()
client.select_db('production_db')
executor.execute('DROP TABLE IF EXISTS `user_profiles`')
executor.close()
client.close()
Record Retrieval
Extrcating data involves executing a SELECT statement and iterating through the returned tuples. The following example filters rows based on a numeric condition.
import pymysql
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
passwd='password',
database='production_db'
)
cursor = conn.cursor()
fetch_stmt = 'SELECT username, age FROM `user_profiles` WHERE age > 20'
cursor.execute(fetch_stmt)
dataset = cursor.fetchall()
for entry in dataset:
print(f'Name: {entry[0]}, Age: {entry[1]}')
cursor.close()
conn.close()