SQL语句参数化__封装
来源:互联网 发布:卡尔曼滤波算法讲解 编辑:程序博客网 时间:2024/05/20 22:01
封装SQL语句参数化(以下代码写为sqlcanshuhua.py文件)
# encoding=utf-8from 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函数里面了
- 运行:
- 调用cha_all方法:
from sqlcanshuhua import *xtz = MysqlHelper(user='root',passwd='123',db='test')sql = 'SELECT * FROM students'xtz.cha_all(sql)
- 运行:
阅读全文
0 0
- SQL语句参数化__封装
- SQL语句参数化
- 参数化SQL语句
- 参数化SQL语句
- 参数化SQL语句
- 参数化SQL语句
- 【mysql】sql语句参数化
- 参数化sql查询语句,书写安全的SQL语句
- 参数化SQL语句,分页SQL语句SQLHELP
- 参数化SQL语句 分页查询SQL语句
- 性能攸关的sql语句参数化
- SqlCommand 参数化输入SQL语句
- Oracle 中参数化SQL 语句 写法
- 何种情况下sql语句参数化
- C# 使用参数化SQL语句
- SQL语句参数化(用%s)
- SQL语句创建参数
- sql hql语句参数
- 嘿,你的手机里有个人工智能芯片等待查收!
- 动画资源
- 谷歌的AI将乌龟认成步枪,这为何是个大问题
- Linux中的swap分区
- 社交媒体充满谎言,搜索引擎撕开真相
- SQL语句参数化__封装
- Shell变量概述
- ros 循环
- 用户自定义变量
- 解决putty登录后输入卡顿问题
- PHP四种基本排序算法
- Bash的环境变量
- Map集合练习
- Python 模块安装error: Microsoft Visual C++ 14.0 is required...问题解决方案