#!/usr/bin/python
import mysql.connector
# Establish the connection
try:
connection = mysql.connector.connect (
# Replace with your MySQL server host
host="undcemmysql.mysql.database.azure.com",
# Replace with your MySQL username
user="user_id",
# Replace with your MySQL password
password="p-word",
# Replace with your database name
database="user_id"
)
if connection.is_connected( ):
print( "Connected to MySQL database" )
# Create a cursor object
cursor = connection.cursor( )
# Execute a query
# Replace 'your_table' with your table name
cursor.execute( "SELECT * FROM course" )
# Fetch and display the results
results = cursor.fetchall( )
for row in results:
print( row )
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
# Close the connection
if connection.is_connected( ):
cursor.close( )
connection.close( )
print( "MySQL connection is closed" )
|
Compile and run the script.
For example,
shell⯈ /usr/bin/python py-mysql.py
|