Categories
Python Answers

How to connect to a MySQL database in Python?

Spread the love

Sometimes, we want to connect to a MySQL database in Python.

In this article, we’ll look at how to connect to a MySQL database in Python.

How to connect to a MySQL database in Python?

To connect to a MySQL database in Python, we can use the MySQLdb package.

To install it, we run

pip install MySQL-python
pip install MySQL-python-connector

Then we use it by writing

import MySQLdb

db = MySQLdb.connect(host='localhost', user='john', passwd='pass',
                     db='jonhydb')

cur = db.cursor()

cur.execute('SELECT * FROM YOUR_TABLE_NAME')

for row in cur.fetchall():
    print row[0]

db.close()

to connect to the database with

db = MySQLdb.connect(host='localhost', user='john', passwd='pass',
                     db='jonhydb')

Then we get the cursor with

cur = db.cursor()

Then we make a query with

cur.execute('SELECT * FROM YOUR_TABLE_NAME')

Then we get the select results with fetchall.

And then we call close to close the database connection once we’re done.

Conclusion

To connect to a MySQL database in Python, we can use the MySQLdb package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *