5.3 Connecting to Database Using MySQL
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
The mysql.connector provides the connect() method used to
create a connection between the MySQL database and the Python application. The
syntax is given below.
Syntax:
Conn_obj= mysql.connector.connect(host = <hostname>,
user = <username>, passwd = <password>)
The connect() function accepts the following
arguments.
Hostname – It represents the server name or IP
address on which MySQL is running.
Username – It represents the name of the user that we use to work
with the MySQL server. By default, the username for the MySQL database is root.
Password – The password is provided at the time of installing the
MySQL database. We don’t need to pass a password if we are using the root.
Database – It specifies the database name which we want to connect.
This argument is used when we have multiple databases.
In the following example we will be connecting to MySQL
database using connect()
Example:
- Python3
|
# Python program to connect # to mysql database import mysql.connector # Connecting from the server conn = mysql.connector.connect(user = 'username', host
= 'localhost', database
= 'database_name') print(conn) # Disconnecting from the server conn.close() |
Output:
![]()
Also for the same, we can use connection.MySQLConnection()
class instead of connect():
Example:
- Python3
|
# Python program to connect # to mysql database 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() |
Output:
![]()
Another way is to pass the dictionary in the connect()
function using ‘**’ operator:
Example:
- Python3
|
# Python program to connect # to mysql database 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() |
Output:
![]()
Example
- Python3
|
# importing required libraries import mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="gfg" ) # preparing a cursor object cursorObject = dataBase.cursor() # creating database cursorObject.execute("CREATE DATABASE
geeks4geeks") |