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 pymysqlWhat is pymysql and why use it?
Key features and capabilities
Installation instructions
Basic usage examples
Common use cases
Best practices and tips
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()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()connectEstablishes a connection to the MySQL database using pymysql
cursorCreates a new cursor to execute SQL queries