# pymysql实现对数据库增删改查 **Repository Path**: geduo777/python-mysql ## Basic Information - **Project Name**: pymysql实现对数据库增删改查 - **Description**: 回忆回忆对数据库操作的封装 - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-06-25 - **Last Updated**: 2021-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # pymysql实现对数据库增删改查 #### 介绍 回忆回忆对数据库操作的封装 #### 软件架构 软件架构说明:python + pymysql #### 使用说明 ```python import pymysql import traceback class db_test(): __conn = None __cur = None # 连接数据库 @classmethod def __db_connect(cls): if cls.__conn is None: cls.__conn = pymysql.connect(host="数据库地址", user="账号", passwd="密码", database="数据库") return cls.__conn # 创建游标 @classmethod def __db_cursor(cls): if cls.__cur is None: cls.__cur = cls.__db_connect().cursor() return cls.__cur # 执行sql @classmethod def sql_data(cls,sql): try: cursor = cls.__db_cursor() cursor.execute(sql) if sql.split(" ")[0].lower() == "select": return cursor.fetchall() else: cls.__db_connect().commit() return cursor.rowcount except: # 事务回滚返回错误数据 cls.__db_connect().rollback() traceback.print_exc() finally: # 关闭游标数据库连接 cls.__close_cursor() cls.__close_connect() @classmethod def __close_cursor(cls): if cls.__cur is not None: cls.__db_cursor().close() cls.__cur = None @classmethod def __close_connect(cls): if cls.__conn is not None: cls.__db_connect().close() cls.__conn = None if __name__ == '__main__': db = db_test() sql = "sql语句" db.sql_data(sql) ``` #### 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request #### 特技 1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md 2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) 3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) 6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)