python MySQL module provides access to python mysqlclient to connect with Mysql Server Database. This blog provides mysqldb python install guidelines to download mysql connector for pythonto and install python mysqlclient library in local machine.
Connect to MySQL in Python using PyMySQL
Getting Started
MySQL is one of the most popular open-source relational database systems. Python, with its rich ecosystem of libraries, makes it easy to interact with MySQL databases. In this guide, we'll walk through how to connect to a MySQL database using Python, perform basic queries, and close the connection properly.
PyMySQL
is a lightweight and easy-to-use library that allows you to connect to MySQL databases directly from Python. It's a great alternative to MySQL-python
(which is outdated) and is compatible with modern Python versions.
Installing PyMySQL
is not a big task for Python developers. A single line of command installs PyMySQL library into a machine. Before installing PyMySQL
make sure that Python and pip are installed in your machine.
If you are new in Python, refer my previous posts to install Python and pip. These two articles are helping to install Python and pip. Pip is a Python Package Manager tool that helps to install Python packages or modules into the machine. Hence before installing any packages or modules pip must have installed in the machine.
Install MySQL Connector Python PyMySQL
The below commands are to install python mysql connectorin local machine.
Windows pip install PyMySQL
ubuntu
sudo -H pip install PyMySQL
Demonstration
This demonstration is conducted in Microsoft Windows 10 and applicable in Windows only, to install the PyMySQL
, follow the below steps.
- Press Windows Key+R key
- Enter cmd.exe and press Enter
- The command prompt will be appeared
- Use below command and press Enter.
pip install PyMySQL
- The installation process will be started, if everything going fine then the package or module will be installed successfully.
mysqldb python install(mysql_python)
Python Connect to MySQL Database
To connect the MySQL database, you must know the details database you want to connect. Below are the parameters required to connect to mysql from Python.
- Host Name:- Server name or Ip address on which MySQL is running. if you are running on localhost, then you can use localhost, or it’s IP
- Database Name:- Database name to which you want to connect.
- Username:- The username that you use to work with MySQL Server. The default username for the MySQL database is a root
- Password:- Password is given by the user at the time of installing the MySQL database. If you are using root then you won’t need the password.
Connecting to the Database
import pymysql
# Define your database connection settings
config = {
"host": "localhost",
"user": "your_username",
"password": "your_password",
"database": "your_database"
}
# Create a connection
try:
connection = pymysql.connect(**config)
print("Connected to MySQL using PyMySQL!")
# Create a cursor object
cursor = connection.cursor()
# Execute a simple query
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print("MySQL version:", version[0])
except pymysql.MySQLError as e:
print("MySQL error:", e)
finally:
if 'connection' in locals() and connection.open:
cursor.close()
connection.close()
print("🔒 Connection closed")
Performing a Query
try:
connection = pymysql.connect(**config)
cursor = connection.cursor()
# Fetch all rows from a table
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
for row in rows:
print(row)
except pymysql.MySQLError as e:
print("Query error:", e)
Inserting Data
try:
connection = pymysql.connect(**config)
cursor = connection.cursor()
# Parameterized query to prevent SQL injection
query = "INSERT INTO your_table (name, age) VALUES (%s, %s)"
data = ("Alice", 30)
cursor.execute(query, data)
connection.commit()
print(f"{cursor.rowcount} row(s) inserted.")
except pymysql.MySQLError as e:
print("Insert error:", e)
connection.rollback()
Querying Data with using
Statement
with pymysql.connect(**config) as connection:
with connection.cursor() as cursor:
cursor.execute("SELECT NOW()")
print("Current time:", cursor.fetchone()[0])
Summary
Connecting Python to MySQL is straightforward with the right tools. Whether you're building a small script or a full web application, mastering this connection is a foundational skill for working with data.
Thanks