Connect to MySQL in Python

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.

  1. Press Windows Key+R key
  2. Enter cmd.exe and press Enter
  3. The command prompt will be appeared
  4. Use below command and press Enter.
     pip install PyMySQL  
    
  5. The installation process will be started, if everything going fine then the package or module will be installed successfully.
    download mysql connector for python
    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.

  1. 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
  2. Database Name:- Database name to which you want to connect.
  3. Username:- The username that you use to work with MySQL Server. The default username for the MySQL database is a root
  4. 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

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال