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.

This entry was posted in Python and tagged on by .
Unknown's avatar

About SandeepSingh

Hi, I am working in IT industry with having more than 15 year of experience, worked as an Oracle DBA with a Company and handling different databases like Oracle, SQL Server , DB2 etc Worked as a Development and Database Administrator.

Leave a Reply