Connecting to MYSQL with Python 2 in three steps

1 - Setting

You must install a MySQL driver before doing anything. Unlike PHP, Only the SQLite driver is installed by default with Python. The most used package to do so is MySQLdb but it's hard to install it using easy_install. Please note MySQLdb only supports Python 2.

For Windows user, you can get an exe of MySQLdb.

For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)

For Mac, you can install MySQLdb using Macport.

2 - Usage

After installing, Reboot. This is not mandatory, But it will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

Then it is just like using any other package :

#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="john",         # your username
                     passwd="megajonhy",  # your password
                     db="jonhydb")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")

# print all the first cell of all the rows
for row in cur.fetchall():
    print row[0]

db.close()

Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. A good starting point.

3 - More advanced usage

Once you know how it works, You may want to use an ORM to avoid writing SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is SQLAlchemy.

I strongly advise you to use it: your life is going to be much easier.

I recently discovered another jewel in the Python world: peewee. It's a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, Where using big tools like SQLAlchemy or Django is overkill :

import peewee
from peewee import *

db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')

class Book(peewee.Model):
    author = peewee.CharField()
    title = peewee.TextField()

    class Meta:
        database = db

Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
    print book.title

This example works out of the box. Nothing other than having peewee (pip install peewee) is required.

🌐
PyPI
pypi.org › project › mysql-connector-python
mysql-connector-python · PyPI
# 3rd party packages to unleash the telemetry functionality are installed $ pip install mysql-connector-python[telemetry] This installation option can be seen as a shortcut to install all the dependencies needed by a particular feature.
      » pip install mysql-connector-python
    
Published   Apr 23, 2026
Version   9.7.0
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-example-connecting.html
MySQL :: MySQL Connector/Python Developer Guide :: 5.1 Connecting to MySQL Using Connector/Python
Section 7.1, “Connector/Python Connection Arguments” describes the permitted connection arguments. It is also possible to create connection objects using the connection.MySQLConnection() class: from mysql.connector import (connection) cnx = connection.MySQLConnection(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()
Discussions

How do I connect to a MySQL Database in Python? - Stack Overflow
However, mysql.connector and _mysql give both an import error (though the second option should work according to the documentation). import MySQLdb works, and then MySQLdb.connect... More on stackoverflow.com
🌐 stackoverflow.com
python - ImportError: No module named mysql.connector using Python2 - Stack Overflow
I was facing the similar issue. My env details - Python 2.7.11 pip 9.0.1 CentOS release 5.11 (Final) ... Copy>>> import mysql.connector Traceback (most recent call last): File "", line 1, in ImportError: No module named mysql.connector >>> More on stackoverflow.com
🌐 stackoverflow.com
Python can not import mysql
Hey, I am currently using this code import mysql.connector and it can not find mysql.connector, even though i installed mysql-connector-python… More on reddit.com
🌐 r/mysql
8
5
June 22, 2022
How to import mysql.connector for Python - Stack Overflow
im actually doing a python tutorial for doing a web app with mysql database but when importing mysql connector for python it never recognizes its already install. i have tried configuring the path, More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › python › python_mysql_getstarted.asp
Python MySQL
To test if the installation was successful, or if you already have "MySQL Connector" installed, create a Python page with the following content: ... If the above code was executed with no errors, "MySQL Connector" is installed and ready to be used. Start by creating a connection to the database. Use the username and password from your MySQL database: ... import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword" ) print(mydb) Run example »
🌐
GitHub
github.com › mysql › mysql-connector-python
GitHub - mysql/mysql-connector-python: MySQL Connector/Python is implementing the MySQL Client/Server protocol completely in Python. No MySQL libraries are needed, and no compilation is necessary to run this Python DB API v2.0 compliant driver. Documentation & Download: http://dev.mysql.com/doc/connector-python/en · GitHub
# 3rd party packages to unleash the compression functionality are installed $ pip install mysqlx-connector-python[compression] This installation option can be seen as a shortcut to install all the dependencies needed by a particular feature.
Author   mysql
🌐
PYnative
pynative.com › home › python › databases › python mysql database connection using mysql connector
Python MySQL Database Connection - MySQL Connector Python
March 9, 2021 - import mysql.connector from mysql.connector import Error try: connection = mysql.connector.connect(host='localhost', database='Electronics', user='pynative', password='pynative@#29') if connection.is_connected(): db_Info = connection.get_server_info() print("Connected to MySQL Server version ", db_Info) cursor = connection.cursor() cursor.execute("select database();") record = cursor.fetchone() print("You're connected to database: ", record) except Error as e: print("Error while connecting to MySQL", e) finally: if connection.is_connected(): cursor.close() connection.close() print("MySQL conne
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-mysql
Python MySQL - GeeksforGeeks
Note: For more information, refer to Connect MySQL database using MySQL-Connector Python. After connecting to the MySQL server let's see how to create a MySQL database. For this, we will first create a cursor() object and will then pass the SQL command as a string to the execute() method. The SQL command to create a database is - ... import mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password" ) # preparing a cursor object cursorObject = dataBase.cursor() # creating database cursorObject.execute("CREATE DATABASE gfg")
Published   May 22, 2026
Top answer
1 of 16
1310

Connecting to MYSQL with Python 2 in three steps

1 - Setting

You must install a MySQL driver before doing anything. Unlike PHP, Only the SQLite driver is installed by default with Python. The most used package to do so is MySQLdb but it's hard to install it using easy_install. Please note MySQLdb only supports Python 2.

For Windows user, you can get an exe of MySQLdb.

For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)

For Mac, you can install MySQLdb using Macport.

2 - Usage

After installing, Reboot. This is not mandatory, But it will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

Then it is just like using any other package :

#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="john",         # your username
                     passwd="megajonhy",  # your password
                     db="jonhydb")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")

# print all the first cell of all the rows
for row in cur.fetchall():
    print row[0]

db.close()

Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. A good starting point.

3 - More advanced usage

Once you know how it works, You may want to use an ORM to avoid writing SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is SQLAlchemy.

I strongly advise you to use it: your life is going to be much easier.

I recently discovered another jewel in the Python world: peewee. It's a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, Where using big tools like SQLAlchemy or Django is overkill :

import peewee
from peewee import *

db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')

class Book(peewee.Model):
    author = peewee.CharField()
    title = peewee.TextField()

    class Meta:
        database = db

Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
    print book.title

This example works out of the box. Nothing other than having peewee (pip install peewee) is required.

2 of 16
202

Here's one way to do it, using MySQLdb, which only supports Python 2:

#!/usr/bin/python
import MySQLdb

# Connect
db = MySQLdb.connect(host="localhost",
                     user="appuser",
                     passwd="",
                     db="onco")

cursor = db.cursor()

# Execute SQL select statement
cursor.execute("SELECT * FROM location")

# Commit your changes if writing
# In this case, we are only reading data
# db.commit()

# Get the number of rows in the resultset
numrows = cursor.rowcount

# Get and display one row at a time
for x in range(0, numrows):
    row = cursor.fetchone()
    print row[0], "-->", row[1]

# Close the connection
db.close()

Reference here

Find elsewhere
🌐
Real Python
realpython.com › python-mysql
Python and MySQL Database: A Practical Introduction – Real Python
March 12, 2023 - In many situations, you’ll already have a MySQL database that you want to connect with your Python application. You can do this using the same connect() function that you used earlier by sending an additional parameter called database: ... from getpass import getpass from mysql.connector import connect, Error try: with connect( host="localhost", user=input("Enter username: "), password=getpass("Enter password: "), database="online_movie_rating", ) as connection: print(connection) except Error as e: print(e)
🌐
MySQL
dev.mysql.com › doc › connector-python › en
MySQL :: MySQL Connector/Python Developer Guide
This manual describes how to install and configure MySQL Connector/Python, a self-contained Python driver for communicating with MySQL servers, and how to use it to develop database applications.
🌐
GeeksforGeeks
geeksforgeeks.org › mysql-connector-python-module-in-python
MySQL-Connector-Python module in Python - GeeksforGeeks
March 9, 2020 - To verify the installation, we can use the following steps: ... import mysql.connector mysql.connector.connect(host='localhost', database='database', user='root', password='your password') Output: If you see the following output, it means that ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › connect-mysql-database-using-mysql-connector-python
Connect MySQL database using MySQL-Connector Python - GeeksforGeeks
July 19, 2025 - Conn_obj = mysql.connector.connect( host=<hostname>, user=<username>, passwd=<password>, database=<database_name> # optional ... Hostname: It represents the server name or IP address on which MySQL is running.
🌐
Liquid Web
liquidweb.com › home › connect to mysql using python
Connect to MySQL using Python | Liquid Web
March 4, 2025 - Install the MySQL connector for Python with pip install mysql-connector-python. Import the MySQL connector in your Python code using import mysql.connector.
🌐
OneUptime
oneuptime.com › home › blog › how to use mysql with python's mysql-connector-python
How to Use MySQL with Python's mysql-connector-python
March 31, 2026 - mysql-connector-python is the official MySQL driver developed by Oracle for Python. It allows Python applications to connect to MySQL databases, execute queries, and manage transactions without any external C dependencies (pure Python implementation ...
🌐
Reddit
reddit.com › r/mysql › python can not import mysql
r/mysql on Reddit: Python can not import mysql
June 22, 2022 - Install your dependency(ies): $ pip install mysql-connector-python · Prove that you can import the dep: $ python -c "import mysql.connector"; echo $?
🌐
MakeUseOf
makeuseof.com › home › programming › 4 ways you can connect python to mysql
4 Ways You Can Connect Python to MySQL
June 29, 2022 - Imported mysqlclient. Created a connection object using MySQLdb.connect(). Passed the database configuration details to MySQLdb.connect(). Created a cursor object to interact with MySQL. Used the cursor object to fetch the version of the connected MySQL database. Remember to switch the database details with your own. mysql-connector-python is the official connection driver supported by Oracle.
🌐
PYnative
pynative.com › home › python › databases › install mysql connector python on windows, macos, linux, unix and ubuntu
Install MySQL Connector Python on Windows, MacOs, Linux, Unix and Ubuntu
March 9, 2021 - On Windows, the default MySQL Connector Python installation location is C:\Python.Version\Lib\sitepackages\ . Here Python.version is the Python version you used to install the connector. Type importing MySQL connector using import mysql.connector.
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-connectargs.html
MySQL :: MySQL Connector/Python Developer Guide :: 7.1 Connector/Python Connection Arguments
Connector/Python supports OpenID Connect as of Connector/Python 9.1.0. Functionality is enabled with the authentication_openid_connect_client client-side authentication plugin connecting to MySQL Enterprise Edition with the authentication_openid_connect authentication plugin. These examples enable the plugin with auth_plugin and defines the JWT Identity Token file location with openid_token_file: # Standard connection import mysql.connector as cpy config = { "host": "localhost", "port": 3306, "user": "root", "openid_token_file": "{path-to-id-token-file}", "auth_plugin": "authentication_openid_
🌐
Stack Overflow
stackoverflow.com › questions › 75909749 › how-to-import-mysql-connector-for-python
How to import mysql.connector for Python - Stack Overflow
im actually doing a python tutorial for doing a web app with mysql database but when importing mysql connector for python it never recognizes its already install. i have tried configuring the path,
🌐
A2 Hosting
a2hosting.com › kb › developer-corner › mysql › connecting-to-mysql-using-python
Web Hosting Built to Grow With You | hosting.com
Web hosting that takes you from idea to website to a lasting business. Fast and secure, with free migration, real experts 24/7 and a 99.9% uptime SLA.