【mysqlclient】python3基于mysqlclient封装的数据库增删改查操作
1. 官网
http://mysql-python.sourceforge.net/MySQLdb.html
2. github地址
python2
https://github.com/farcepest/MySQLdb1
python3
https://github.com/PyMySQL/mysqlclient
3. pypi
https://pypi.python.org/pypi/MySQL-python/1.2.5
https://pypi.python.org/pypi/mysqlclient/
4. 安装
python2
pip install MySQL-python==1.2.5
python3
pip install mysqlclient
另一种方式就是源码安装
5. mysql-client封装示例
#!/usr/bin/env python # -*- coding:utf-8 -*- import logging import MySQLdb from MySQLdb import cursors class MySQLdbUtil(object): def __init__(self, host, user, passwd, db, port): self.host = host self.user = user self.passwd = passwd self.db = db self.port = port self.cursor = None self.conn = None def get_connection(self): self.conn = MySQLdb.connect(self.host, self.user, self.passwd, self.db, self.port) def select_one(self, sql): try: self.get_connection() self.cursor = self.conn.cursor(cursors.DictCursor) self.cursor.execute(sql) self.conn.commit() data = self.cursor.fetchone() return data except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def select_many(self, sql): try: self.get_connection() self.cursor = self.conn.cursor(cursors.DictCursor) self.cursor.execute(sql) self.conn.commit() data = self.cursor.fetchall() return data except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def delete_operation(self, sql): try: self.get_connection() cursor = self.conn.cursor() count = cursor.execute(sql) self.conn.commit() return count except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def update_operation(self, sql): try: self.get_connection() cursor = self.conn.cursor() count = cursor.execute(sql) self.conn.commit() return count except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def insert_operation(self, sql): try: self.get_connection() cursor = self.conn.cursor() count = cursor.execute(sql) self.conn.commit() return count except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def close(self): self.cursor.close() self.conn.close() if __name__ == '__main__': client = MySQLdbUtil("192.168.x.xxx", "root", "xxxxx", "test", 3306) result = client.select_many("select * from role;") print(result)
6. MySQLdb示例(python2)
https://zhuanlan.zhihu.com/p/25539328
7. 关于cursor
https://www.cnblogs.com/fireblackman/p/16014467.html
参考链接:
https://sourceforge.net/projects/mysql-python/files/
https://mysqlclient.readthedocs.io/
https://www.runoob.com/python/python-mysql.html