Linux + Python: MySQL Part 2

This marks the fourth post in my Python series. This time, we’re circling back to MySQL to build on what we covered in the first Python + MySQL post—albeit with a slightly more advanced approach.

In this iteration, I’ve incorporated an additional try-except block along with a finally clause to enhance error handling and structure. I admit, the progress might seem incremental, but consistency in daily practice truly pays off over time. I hope you’re also diligently working toward your own goals or projects.

As for me, being a Java developer with aspirations of becoming an Android developer, I know I should dedicate more time to Java and Kotlin. Still, I find Python incredibly enjoyable—especially for experimenting with database-related queries. It’s easy to lose track of time while working with it.

What’s truly wonderful about programming is that no effort is ever wasted. The time you invest in coding, regardless of the language, will always contribute to your growth and understanding.

Now, as mentioned earlier, here’s the updated code:

image 01

Actual code:

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost', 
                    user='username', 
                    password='pw',
                    database='db')

    cursor = connection.cursor(prepared=True)
    sql_query = """ select * from sample_tbl where store_name = 'Amazon' """
    cursor.execute(sql_query)

    for tbl in cursor:
        print(tbl)
   
    connection.commit()
    

except mysql.connector.Error as error:
    print("parameterized query failed {}".format(error))
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

DB:

image 02

Executed result:

image 03

Afterthoughts:

Given Python’s rich ecosystem of libraries for working with spreadsheets and CSV files, I’m tempted to explore some of those fascinating tools in the near future. Until then, see you soon!

Leave a Reply

Your email address will not be published. Required fields are marked *