- Connecting Python to MySQL
Prior to any MySQL database operation, you, first of all, need to connect your Python application to the MySQL server.
To establish the connection, you need to follow the following simple steps:
- Step 1: First of all, import MySQL. Connector.
Import mysql.connector
- Step 2: Now, establish the database connection by entering the correct hostname, username and password. If all or one of these MySQL server credentials is wrong, you’ll definitely receive an error and there will be no connection.
db_connection = mysql.connector.connect( host=”hostname”, user=”username”, passwd=”password”)
- Step 3: Now, test the connection. If your connection is successfully installed, the following should be displayed on your screen.
<mysql.connector.connection.MySQLConnection object at 0x000002338A4C6B00>
The following is an example of an example of a Python MySQL connection:
import mysql.connector
db_connection = mysql.connector.connect(
host=”localhost”,
user=”root”,passwd=”root”
) print(db_connection)