-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnect.py
25 lines (20 loc) · 821 Bytes
/
connect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import mysql.connector
# Initialize a variable to hold the database connection
conn = None
try:
# Attempt to establish a connection to the MySQL database
conn = mysql.connector.connect(host='localhost',
port=3306,
database='pub',
user='<user>',
password='<password>')
# Check if the connection is successfully established
if conn.is_connected():
print('Connected to MySQL database')
except mysql.connector.Error as e:
# Print an error message if a connection error occurs
print(e)
finally:
# Close the database connection in the 'finally' block to ensure it happens
if conn is not None and conn.is_connected():
conn.close()