Skip to content

Instantly share code, notes, and snippets.

@pchatterjee
Created February 27, 2023 00:50
Show Gist options
  • Select an option

  • Save pchatterjee/deacecab7630af3497f2f065c2561369 to your computer and use it in GitHub Desktop.

Select an option

Save pchatterjee/deacecab7630af3497f2f065c2561369 to your computer and use it in GitHub Desktop.
# modules
import pymysql as pm
import sys
from tabulate import tabulate
try:
# connect to mysql platform
conn = pm.connect(host='localhost', user='root', passwd=None, db='quotes-db')
# create the cursor
cur = conn.cursor()
# execute curson with query (using heredoc multi-line string)
cur.execute("""SELECT `qid`,`quote`, `s-name`, `c-name`
FROM `quotes`, `source`, `category_quotes`, `category`
WHERE `qid`=`qid-fk`
AND `sid-fk`=`sid`
AND `cid`=`cid-fk`
AND `c-name`='philosophy'""")
# get the result list
result = cur.fetchall()
# pretty-print using tabulate
print(tabulate(result, headers=['id', 'quote', 'source', 'category'], tablefmt='psql'))
# close cursor and connection
cur.close()
conn.close()
# catch and report any exception
except BaseException as err:
print(f"An error occured: {err}")
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment