MySQL Database Connection: Python

mysql database connection python

MySQL Database Connection: Python


Install the MySQL driver

Python requires the MySQL driver to access the MySQL database.

In this tutorial, we will use the "MySQL Connector" driver.

We recommend that you use PIP to install the "MySQL Connector".

Most likely, PIP is already installed in your Python environment.

python -m pip install mysql-connector


If you already have "MySQL Connector" installed, create a Python page with the following content:


import mysql.connector


Example 1:


Here, USERNAME is your mysql username and PASSWORD is mysql password.




import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="USERNAME",
  passwd="PASSWORD"
)

print(mydb)


Example 2:


Here, USERNAME is your mysql username, PASSWORD is mysql password and DATABASE is database name.




import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="USERNAME",
  passwd="PASSWORD",
  database = "DATABASE"
)

print(mydb)






Comments

Post a Comment