-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy path28.python_mysql
More file actions
55 lines (38 loc) · 1.56 KB
/
Copy path28.python_mysql
File metadata and controls
55 lines (38 loc) · 1.56 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
44
45
46
47
48
49
50
51
52
53
54
55
My complete SQL Masterclass Notes in Tanglish is now live! Covers 30+ topics with syntax, examples, and step-by-step explanations.
Perfect for both beginners and professionals to master SQL easily. Check it out here 👉 https://topmate.io/dataengineering/1697791
====================================================================================
Step 1
pip install mysql-connector-python
Step 2
Code
import mysql.connector
from mysql.connector import Error
try:
# Establish the connection
connection = mysql.connector.connect(
host='localhost', # e.g., 'localhost' or the IP address of your MySQL server
database='your_database', # the name of the database you created
user='your_username', # your MySQL username
password='your_password' # your MySQL password
)
if connection.is_connected():
print("Connected to MySQL database")
# Create a cursor object using the connection
cursor = connection.cursor()
# Define your query (for example, selecting all rows from a table)
query = "SELECT * FROM your_table"
# Execute the query
cursor.execute(query)
# Fetch all rows from the executed query
rows = cursor.fetchall()
# Process the rows
for row in rows:
print(row)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
# Close the cursor and connection
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")