1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import mysql.connector
def queryAllStu(config): output = [] conn = mysql.connector.Connect(**config) cur= conn.cursor() tbl = "STUDENT" stmt_query = "select ID, NAME, AGE, BRD, CREATEDT from {0}".format(tbl) cur.execute(stmt_query) for row in cur.fetchall(): output.append("%2d | %20s | %d | %10s | %18s" % (row[0], row[1], row[2], row[3], row[4])) cur.close() conn.close() return output
def queryById(config, id): output = [] conn = mysql.connector.Connect(**config) cur = conn.cursor() tbl = "STUDENT" stmt_query = "select ID, NAME, AGE, BRD, CREATEDT from {0} where ID = {1}".format(tbl, id) cur.execute(stmt_query) for row in cur.fetchall(): output.append("%2d | %20s | %d | %10s | %18s" % (row[0], row[1], row[2], row[3], row[4])) cur.close() conn.close() return output if __name__ == '__main__': config = { 'host': 'localhost', 'port': 3306, 'database': 'test', 'user': 'root', 'password': '!qaz2wsx', 'charset': 'utf8', 'use_unicode': True, 'get_warnings': True, } output = queryAllStu(config) print('\n'.join(output))
|