STEM with Python – Part 4: Python and MySQL Ⅱ

Incremental yet steady progress…

SQL database is a great toying tool, especially the simple joy that comes with a way to control and clean up the data is unparalleled and the endless discovery the STEM world offers us is simply beautiful. This time around, let’s swing back to MySQL!

So, this is the fourth post on STEM with Python. This time, let’s swing back to MySQL and do a little more advanced version of what we did in the first post of Python + MySQL.

This time around, I added an extra try-except clause as well as finally in it and make it a bit more advanced. I know, I know, my progress is quite incremental, but the daily rituals will get you there eventually. So, I hope you’re also working on your own project or goal.

As for myself, since I’m a Java developer and want to be an Android developer someday, I need to spend more time on Java/Kotlin than on Python though… But since Python is a great language to toy with experimenting with some DB-related queries, I usually forgot about the time.

But what’s great about programming, in general, is that nothing is wasted. None of the hours you spend on coding in whatever language you prefer will eventually be paid off.

Anyways, as I mentioned above, here’s my 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")

The DB:

image 02

Executed result:

image 03

Afterthoughts:

Since Python has a lot of spreadsheet-CSV convertible libraries as well, maybe I want to try those amazing toy tools in the near future! See you soon!

Leave a Reply