-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmysql.py
More file actions
43 lines (37 loc) · 1.26 KB
/
mysql.py
File metadata and controls
43 lines (37 loc) · 1.26 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# mysql_test.py
import mysql.connector
from mysql.connector import Error
def connect_query_close():
try:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="1144",
database="school_db"
)
if conn.is_connected():
print("✅ Connected to MySQL")
cursor = conn.cursor()
cursor.execute("SELECT DATABASE();")
db = cursor.fetchone()
print("Using database:", db[0])
# Example query
cursor.execute("SHOW TABLES;")
tables = cursor.fetchall()
print("Tables in database:")
for tbl in tables:
print(" -", tbl[0])
except Error as err:
if err.errno == mysql.connector.errorcode.ER_ACCESS_DENIED_ERROR:
print("❌ Invalid credentials")
elif err.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR:
print("❌ Database does not exist")
else:
print("❌ Error:", err)
finally:
if 'conn' in locals() and conn.is_connected():
cursor.close()
conn.close()
print("🔒 Connection closed")
if __name__ == "__main__":
connect_query_close()