title: Simple Mysql Wrapper 01 tags: python db mysql h1: This is a simple wrapper for mysql (and I have a simliar one for postgresql), so that for simple stuff, you can write simply: ```py from jda_mysql import Mysql1 class App(Mysql1): def go(self): cur = self.cur cur.execute("SELECT path, filename, size_bytes FROM table LIMIT 10") self.show_table(cur,title="My Files") App(host="servername",dbname="files").main() ``` ## jda_mysql.py ```py import mysql.connector from mysql.connector.errors import DatabaseError import sys try: from rich.table import Table from rich.console import Console except ModuleNotFoundError: pass class Mysql1: def __init__(self,host="localhost",user="mrturnip",password="floink",dbname="",**kw): self.host = host self.user = user self.password = password self.dbname = dbname self.kw = kw def show_table(self,cur,title=None): try: table = Table(title=title) console = Console() except NameError: print(f"Table unavailable, need rich module",file=sys.stderr) return colnames = cur.column_names for col in colnames: table.add_column(col) for row in cur: table.add_row(*map(str,row)) console.print(table) def go(self): print("Need to override go()") def main(self): try: self.db = mysql.connector.connect(host=self.host,user=self.user,password=self.password,database=self.dbname) except DatabaseError as e: print(f"DatabaseError(connect): {e}",file=sys.stderr) return 1 try: self.cur = self.db.cursor() self.go() except DatabaseError as e: print(f"DatabaseError(go): {e}",file=sys.stderr) return 1 self.db.commit() self.db.close() return 0 ```