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
| import mysql.connector from datetime import datetime from datetime import date
def main(config): conn = mysql.connector.Connect(**config) cur = conn.cursor() tbl = "STUDENT" created = datetime.now() students = (("Jack", 27, date(1990, 3, 27), created), ("Zhao San", 21, date(1995, 10, 21), created), ("Zhao San", 1122, date(1995, 10, 21), created)) stmt_insert = "Insert into {0} (name, age, brd, CREATEDT) values (%s, %s, %s, %s)".format(tbl) try: cur.executemany(stmt_insert, students) except (mysql.connector.errors.Error, TypeError) as exc: conn.rollback() print("Roll Back, Insert has error :", exc) else: conn.commit() finally: cur.close() conn.close() if __name__ == '__main__': config = { 'host': 'localhost', 'port': 3306, 'database': 'test', 'user': 'root', 'password': '!qaz2wsx', 'charset': 'utf8', 'use_unicode': True, 'get_warnings': True, } main(config)
|