How to connect to mysql database using python
Different ways to connect to mysql using python
Published in
2 min readSep 28, 2022
Introduction:
This article discusses how to connect to a mysql database using python
. We will review three ways of connecting to mysql
using python
If you’re looking for an introduction to basic SQL
queries, please read this post.
Connect to mysql using sql connector:
The connection to mysql
can be established using mysql-connector-python
library.
$pip install mysql-connector-python
Collecting mysql-connector-python
Using cached mysql_connector_python-8.0.30-cp39-cp39-macosx_11_0_x86_64.whl (5.1 MB)
Collecting protobuf<=3.20.1,>=3.11.0
Using cached protobuf-3.20.1-cp39-cp39-macosx_10_9_x86_64.whl (962 kB)
Installing collected packages: protobuf, mysql-connector-python
Successfully installed mysql-connector-python-8.0.30 protobuf-3.20.1import mysql.connector
def connect_to_mysql() -> mysql.connector:
"""
Establish the database connection.
"""
cnx = mysql.connector.connect(
user="username",
password="password",
host="hostname",
database="databasename",
connection_timeout=10000
)
return cnx