← Back to Libraries🗄️ Database & SQL
📦

Mastering pymysql: The Ultimate Python MySQL Client Guide

Discover the power of pymysql in this comprehensive mysql python guide. Learn how to effectively use this pure MySQL client in your Python projects with our detailed pymysql tutorial.

pip install pymysql

Overview

What is pymysql and why use it?

Key features and capabilities

Installation instructions

Basic usage examples

Common use cases

Best practices and tips

Common Use Cases

Code Examples

Getting Started with pymysql

import pymysql

# Establish a connection to the database
connection = pymysql.connect(
    host='localhost',
    user='your_username',
    password='your_password',
    database='your_database'
)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@pythonacademy.io', 'very_password'))

    # Connection is not autocommit by default. So you must commit to save your changes.
    connection.commit()
finally:
    connection.close()

Advanced pymysql Example

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(
    host='localhost',
    user='your_username',
    password='your_password',
    database='your_database',
    cursorclass=pymysql.cursors.DictCursor
)

try:
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@pythonacademy.io',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

Alternatives

Common Methods

connect

Establishes a connection to the MySQL database using pymysql

cursor

Creates a new cursor to execute SQL queries

More Database & SQL Libraries