Establish connection and execute SQL query in Python
Example of using the Select query from MySQL database in Python program
import mysql.connector
# Connect to MySQL database
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
cursor = cnx.cursor()
# Fetch the script from the table
query = "SELECT employee_name FROM employees"
#Execute the script
cursor.execute(query)
# rFetch the results and print them
results = cursor.fetchall()
print(f"Results for {db_name}:")
for row in results:
print(row)
# Commit changes to database
cnx.commit()
# Close the cursor and database connection
cursor.close()
cnx.close()
This code connects to the MySQL database using the mysql-connector-python
library, and executes the script using the cursor.execute()
method. Finally, it commits any changes made to the database and closes the connection.