Querying data from a MySQL database using Python

In this post we will check how to connect and read data from MySQL database using Python. To connect and query data from that remote database, you need a usernamepassword, and the name of the database. These are written inside the Python script below. You also need a Python library that interacts with MySQL databases. There are many, but I prefer mysql.connector. To install it, simply execute pip install mysql-connector  or pip3 install mysql-connector depending on whether you use pip or pip3. Once you install the library you can go ahead and try this working example:

import mysql.connector
word = input("Enter a word in English and press Enter: ")
con = mysql.connector.connect(
    user="root", 
    password = "root", 
    host="127.0.0.1", 
    database = "student_db"
)
cursor = con.cursor()
query = cursor.execute("SELECT * FROM Dictionary WHERE Expression = '%s'" % word)
results = cursor.fetchall()
if results:
    for result in results:
        print(result[1])
else:
    print("We couldn't find any results about that.")

 

Python 12

FOLLOW US ON LinkedIn



Explore Tutu'rself