Connect MySQL database using MySQL-Connector Python

While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.

MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies.

Connecting to the Database

In the following example we will be connecting to MySQL database using connect()

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to connect
# to mysql databse
  
  
import mysql.connector
  
  
# Connecting from the server
conn = mysql.connector.connect(user = 'username',
                               host = 'localhost',
                              database = 'databse_name')
  
print(conn)
  
# Disconnecting from the server
conn.close()

chevron_right


Output:



python-mysql-connect-1

Also for the same, we can use connection.MySQLConnection() class instead of connect():

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to connect
# to mysql databse
  
  
from mysql.connector import connection
  
# Connecting to the server
conn = connection.MySQLConnection(user = 'username'
                              host = 'localhost',
                              database = 'database_name')
  
print(conn)
  
# Disconnecting from the server
conn.close()

chevron_right


Output:

python-mysql-connect-2

Another way is to pass the dictionary in the connect() function using ‘**’ operator:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to connect
# to mysql databse
  
  
from mysql.connector import connection
  
  
dict = {
  'user': 'root',
  'host': 'localhost',
  'database': 'College'
}
  
# Connecting to the server
conn = connection.MySQLConnection(**dict)
  
print(conn)
  
# Disconnecting from the server
conn.close()

chevron_right


Output:

python-mysql-connect-3




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.