Python中使用pymsql连接数据库
2021/11/6 19:11:55
本文主要是介绍Python中使用pymsql连接数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
from app import app import pymysql import config class Database: aurl = config.aurl user = config.user password =config.password db = config.db charset = config.charset def __init__(self): self.connection = pymysql.connect(host=self.aurl, user=self.user, password=self.password, database=self.db, charset=self.charset) self.cursor = self.connection.cursor() #插入 def insert(self, query, params): inset_id=0 try: self.cursor.execute(query, params) inset_id=self.connection.insert_id() #返回插入行的id self.connection.commit() return inset_id except Exception as e: # 若有异常就回滚; self.connection.rollback() app.logger.info("Error: insert to fecth data", e) return inset_id finally: self.connection.close() # 关闭连接 #查询 def query(self, query, params): try: self.cursor.execute(query, params) return self.cursor.fetchall() except Exception as e: print("Error: unable to fecth data") app.logger.info("Error: query to fecth data",e) finally: self.connection.close() # 关闭连接 #查询一个 def queryone(self, query, params): try: self.cursor.execute(query, params) return self.cursor.fetchall() except Exception as e: print("Error: unable to fecth data") app.logger.info("Error: queryone to fecth data",e) finally: self.connection.close() # 关闭连接 #更新 def update(self,sql,params): row=0 try: row=self.cursor.execute(sql, params) self.connection.commit() return row except Exception as e: # 若有异常就回滚; self.connection.rollback() app.logger.info("Error: update to fecth data", e) return row finally: self.connection.close() # 关闭连接 # 删除 def delete(self,sql,params): row=0 try: row=self.cursor.execute(sql, params) self.connection.commit() return str(row) except Exception as e: # 若有异常就回滚; self.connection.rollback() app.logger.info("Error: delete to fecth data", e) return row finally: self.connection.close() # 关闭连接 # def __del__(self): # self.connection.close() if __name__ == '__main__': passView Code
这篇关于Python中使用pymsql连接数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型