OneCompiler

Connect to MySQL database using Python

399


In this post, we will see how to connect to a MySQL Database using Python.

What is MySQL?

MySQL is an open-source, free, and very popular relational database management system that is developed, distributed, and supported by Oracle corporation.

How to connect to MySQL Database

1. Using connect() method

connect() method is used to connect to MySQL database from Python.

import mysql.connector 

# Connecting to the server
con = mysql.connector.connect(user = 'your_username', 
							host = 'localhost', 
							database = 'your_databse_name') 

print(con) 

# The below line disconnects from the server 
conn.close() 

2. Using connection.MySQLConnection() class

We can also use connection.MySQLConnection() class.

from mysql.connector import connection 
  
con = connection.MySQLConnection(user = 'username',  
                              host = 'localhost', 
                              database = 'database_name') 
  
print(con) 
con.close()