Create connection with MySQL in python

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

# rFetch the results and print them
    results = cursor.fetchall()
    print(f"Results for {db_name}:")
    for row in results:

# Commit changes to database

# Close the cursor and database connection

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.