In Python, the easy way to connect mysql is used mysql-connector-python
package. which provides an interface for Python to interact with MySQL databases.
Install mysql-connector-python
You can use pip
to install.
pip install mysql-connector-python
Import Library
You should import mysql.connector
library in python script before connecting mysql server.
Connect MySQL
You can use mysql.connector.connect()
method to establish a connection to a MySQL database.
Syntax
mysql.connector.connect( host=None, user=None, password=None, database=None, port=None, unix_socket=None, auth_plugin='mysql_native_password', charset='utf8' )
Parameters
host (str)
: The host name or IP address of the MySQL server. Commonly set to “localhost
” if the server is running on the same machine.
user (str)
: The username used to authenticate against the MySQL server.
password (str)
: The password used to authenticate the specified user against the MySQL server.
database (str)
: The name of the database to connect to. This parameter is optional and can be specified after the connection is established using the connect()
function.
port (int)
: (Optional) The port number where the MySQL server is listening. The default port for MySQL is 3306
.
unix_socket (str)
: (Optional) The Unix socket file to use for connections. This parameter is typically used when connecting to a MySQL server running on the local machine.
auth_plugin (str)
: (Optional) The authentication plugin to use when connecting to the MySQL server. The default value is ‘mysql_native_password
‘.
charset (str)
: (Optional) The character set used for the connection. The default is ‘utf8
‘.
Return Value
It returns a mysql connection
Example
import mysql.connector # Establish connection to MySQL server try: connection = mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) if connection.is_connected(): print("Connected to MySQL server") # Perform operations here except mysql.connector.Error as error: print("Error connecting to MySQL server:", error) finally: # Close the connection if 'connection' in locals(): connection.close() print("MySQL connection is closed")
Close Connection
You can use connection.close()
to close the connection between python and MySql server.