本节内容为方便大家复制,所有内容都写在了引用模块。
pip3 config set global.index-url https://repo.huaweicloud.com/repository/pypi/simple pip3 config list pip3 install --upgrade pip pip3 install pymysql
import pymysql class DBHelper(): def __init__(self): # 数据库连接参数 self.host = "rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com" self.user = "qwe8403000" self.pwd = "Qwe8403000" self.db = "mytest" self.charset = "utf-8" # 获取游标 def getConnect(self): if not self.db: raise(NameError, "没有设置数据库信息") self.conn = pymysql.connect(host=self.host, port=3306, user=self.user, passwd=self.pwd, db=self.db, charset="utf8mb4") # 按照字典的方式返回 cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) if not cursor: raise(NameError, "连接数据库失败") else: return cursor # 查 def query(self, sql): cursor = self.getConnect() cursor.execute(sql) result = cursor.fetchall() # 获取查询的所有数据 # 查询完毕后必须关闭连接 self.conn.close() return result # 增删改查 def excute(self, sql): cursor = self.getConnect() cursor.execute(sql) self.conn.commit() self.conn.close()
调用示例:
from DBHelper import DBHelper db=DBHelper() db.excute("sql") result=db.query("sql") print(result)
希望对大家有所帮助,复制起来很方便。