|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +__auth__ = 'zone' |
| 3 | +__date__ = '2019/8/4 下午3:33' |
| 4 | +''' |
| 5 | +公众号:zone7 |
| 6 | +小程序:编程面试题库 |
| 7 | +''' |
| 8 | + |
| 9 | +import contextlib |
| 10 | +import pymysql |
| 11 | + |
| 12 | +# 原始用法 |
| 13 | +conn = pymysql.connect() |
| 14 | +cur = conn.cursor() |
| 15 | +sql = "select * from users" |
| 16 | +cur.execute(sql) |
| 17 | +print(cur.fetchone()) |
| 18 | +conn.commit() |
| 19 | +cur.close() |
| 20 | +conn.close() |
| 21 | + |
| 22 | + |
| 23 | +class MysqlDb(): |
| 24 | + def __init__(self, database, host="localhost", user="root", prot=3306, password="root", charset="utf8mb4"): |
| 25 | + self.conn = pymysql.connect(host=host, user=user, password=password, port=prot, database=database, |
| 26 | + cursorclass=pymysql.cursors.DictCursor, charset=charset) |
| 27 | + self.cur = self.conn.cursor() |
| 28 | + |
| 29 | + def __enter__(self): |
| 30 | + return self.cur |
| 31 | + |
| 32 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 33 | + self.conn.commit() |
| 34 | + self.cur.close() |
| 35 | + self.conn.close() |
| 36 | + |
| 37 | + |
| 38 | +with MysqlDb(database="test", ) as db: |
| 39 | + sql = "select * from users" |
| 40 | + db.execute(sql) |
| 41 | + print(db.fetchone()) |
| 42 | + intert_sql = "INSERT INTO `users` (`name`, `password`, `age`, `sex`) VALUES (%s, %s, %s, %s)" |
| 43 | + db.execute(intert_sql, ('zone7', 'pwd', "18", "man")) |
| 44 | + |
| 45 | + |
| 46 | +@contextlib.contextmanager |
| 47 | +def get_mysql_cur(database, host="localhost", user="root", prot=3306, password="root", charset="utf8mb4"): |
| 48 | + conn = pymysql.connect(host=host, user=user, password=password, port=prot, database=database, |
| 49 | + cursorclass=pymysql.cursors.DictCursor, charset=charset) |
| 50 | + cur = conn.cursor() |
| 51 | + yield cur |
| 52 | + conn.commit() |
| 53 | + cur.close() |
| 54 | + conn.close() |
| 55 | + |
| 56 | + |
| 57 | +with get_mysql_cur(database="test", ) as db: |
| 58 | + sql = "select * from users" |
| 59 | + db.execute(sql) |
| 60 | + print(db.fetchone()) |
0 commit comments