connect()
Method of MySQL Connector Interface
The connect()
method in MySQL Connector is used to establish a connection to a MySQL database. This method is part of the mysql.connector
module in Python, which allows you to interact with MySQL databases.
Arguments of connect()
Method
The connect()
method can take several arguments to specify the connection parameters. Here are the most commonly used arguments:
- host: The hostname or IP address of the MySQL server (default is
'127.0.0.1'
). - user: The username to use when connecting to the server.
- password: The password to use when connecting to the server.
- database: The name of the database to use once connected.
- port: The port number to use for the connection (default is
3306
). - auth_plugin: The authentication plugin to use (e.g.,
'mysql_native_password'
). - use_pure: Whether to use the pure Python implementation of MySQL Connector (default is
True
). - charset: The character set to use for the connection.
- collation: The collation to use for the connection.
- ssl_ca: The path to the Certification Authority certificate.
- ssl_cert: The path to the client certificate.
- ssl_key: The path to the client key.
Example Python Code to Create and Connect to student_DB
Below is a Python script that demonstrates how to create a database named student_DB
and connect to it using the mysql.connector
module. Make sure you have the MySQL server running and the mysql-connector-python
package installed.
import mysql.connector
from mysql.connector import errorcode
# Connection details
host = 'localhost' # or '127.0.0.1'
user = 'root' # Replace with your MySQL username
password = 'your_password' # Replace with your MySQL password
# Step 1: Connect to the MySQL server
try:
cnx = mysql.connector.connect(
host=host,
user=user,
password=password
)
cursor = cnx.cursor()
print("Successfully connected to MySQL server")
# Step 2: Create a new database named student_DB
try:
cursor.execute("CREATE DATABASE student_DB")
print("Database student_DB created successfully")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_DB_CREATE_EXISTS:
print("Database student_DB already exists.")
else:
print(f"Failed to create database: {err}")
# Step 3: Connect to the newly created database
cnx.database = 'student_DB'
print("Successfully connected to student_DB")
# Further database operations can be performed here
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
# Clean up and close the connection
if 'cursor' in locals():
cursor.close()
if 'cnx' in locals():
cnx.close()
print("Connection closed")
Explanation
- Connection Details: The script defines the connection parameters, including
host
,user
, andpassword
. - Connect to MySQL Server:
- The script attempts to connect to the MySQL server using
mysql.connector.connect()
. - If the connection is successful, it creates a cursor object to execute SQL queries.
- Create Database:
- The script tries to create a new database named
student_DB
using theCREATE DATABASE
SQL command. - If the database already exists, it catches the specific error and prints an appropriate message.
- Connect to the New Database:
- The script sets the
cnx.database
attribute tostudent_DB
, switching the connection to the newly created database.
- Error Handling:
- The script includes error handling for various potential issues, such as connection failures and database creation errors.
- Cleanup:
- The script ensures that the cursor and connection are properly closed in the
finally
block to release resources.
This script provides a basic example of how to use the connect()
method to interact with a MySQL database using the mysql.connector
module in Python.