Python MySQL: Database Connection
Establishing a connection between Python and MySQL is the first step in managing your databases. This section will guide you through creating a connection to your MySQL database.
Connecting to MySQL Database
To connect to a MySQL database, use the connect()
method from the MySQL connector library. The method requires several parameters like hostname, username, password, and the database you wish to connect to.
Database Connection
import mysql.connector
# Establishing a connection
connection = mysql.connector.connect(
host='localhost',
user='root',
password='yourpassword'
)
if connection.is_connected():
print("Successfully connected to MySQL")
connection.close()
Output
Successfully connected to MySQL
Explanation of Code Example
In this example:
- We use the mysql.connector.connect()
function to establish a connection with the MySQL server.
- The is_connected()
method checks if the connection is successful.
- Finally, we close the connection using connection.close()
.