SQL语句参数化__封装

封装SQL语句参数化(以下代码写为sqlcanshuhua.py文件)

# encoding=utf-8
from pymysql import *

class MysqlHelper:
    def __init__(self,user,passwd,db,host='localhost',port=3306,charset='utf8'):  #注意这里有默认值的变量一定要放在没有默认值变量的后面
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db
        self.charset = charset

    def open(self):
        self.conn=connect(host=self.host,port=self.port,db=self.db,
                     user=self.user,passwd=self.passwd ,charset=self.charset)
        self.cursor=self.conn.cursor()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def cud(self,sql,params):  #增加、修改、删除
        try:
            self.open()

            self.cursor.execute(sql,params)
            self.conn.commit()
            print('ok')
            self.close()
        except Exception as e:
            print(e)

    def cha_all(self,sql,params=()):  #查询获取多个值
        try:
            self.open()

            self.cursor.execute(sql,params)
            result = self.cursor.fetchall()

            self.close()

            return result
        except Exception as e:
            print(e.message)

  • 调用cud方法:
from sqlcanshuhua import *

xtz = MysqlHelper(user='root',passwd='123',db='test')

name=input('请输入学生姓名:')
gender = input('请输入学生性别:')
params = [name,gender]
sql = 'INSERT students(sname,gender) VALUES(%s,%s)'

xtz.cud(sql,params) #这里不用再单独调用open和close,因为他们已经封装到cud函数里面了
  • 运行:

SQL语句参数化__封装_第1张图片

  • 调用cha_all方法:
from sqlcanshuhua import *
xtz = MysqlHelper(user='root',passwd='123',db='test')
sql = 'SELECT * FROM students'
xtz.cha_all(sql)
  • 运行:
    SQL语句参数化__封装_第2张图片

你可能感兴趣的:(mysql)