How do I connect to a MySQL database using a python program?
Best way to connect to MySQL from python is to Use MySQL Connector/Python because it is official Oracle driver for MySQL for working with Python and it works with both Python 3 and Python 2.
follow the steps mentioned below to connect MySQL
install connector using pip
pip install mysql-connector-python
or you can download the installer from https://dev.mysql.com/downloads/connector/python/
Use connect()
method of mysql connector python to connect to MySQL.pass the required argument to connect()
method. i.e. Host, username, password, and database name.
Create cursor
object from connection object returned by connect()
method to execute SQL queries.
close the connection after your work completes.
Example:
import mysql.connector
from mysql.connector import Error
try:
conn = mysql.connector.connect(host='hostname',
database='db',
user='root',
password='passcode')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchall()
print ("You're connected to - ", record)
except Error as e :
print ("Print your error msg", e)
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
Reference - https://pynative.com/python-mysql-database-connection/
Important API of MySQL Connector Python
For DML operations - Use cursor.execute()
and cursor.executemany()
to run query. and after this use connection.commit()
to persist your changes to DB
To fetch data - Use cursor.execute()
to run query and cursor.fetchall()
, cursor.fetchone()
, cursor.fetchmany(SIZE)
to fetch data