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
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.

Advertisement

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.