Connect MySQL database using mysql-connector-python
Python script establishing database connection using mysql-connector-python library.
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='your_password',
database='company_db'
)
if connection.is_connected():
db_info = connection.get_server_info()
print(f"Connected to MySQL Server v{db_info}")
cursor = connection.cursor()
cursor.execute("SELECT DATABASE();")
record = cursor.fetchone()
print("Active Database:", record[0])
except Error as e:
print("Error connecting to MySQL:", e)
finally:
if 'connection' in locals() and connection.is_connected():
connection.close()
print("MySQL connection closed.")Connected to MySQL Server v8.0.36 Active Database: company_db MySQL connection closed.