mysql 参数化 c_MySQL(16):参数化、封装

1.sql语句参数化

创建testInsertParam.py文件,向学生表中插入一条数据#encoding=utf-8

import pymysql

try:

conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')

cs1=conn.cursor()

students_n=input("请输入学生姓名:")

params=[students_n]    #将输入的要操作的值放入列表中

count=cs1.execute('insert into students(sname) values(%s)',params)

#不管values对应的值是什么类型,都用%s占位符表示

print(count)

conn.commit()

cs1.close()

conn.close()

except Exception as e:

print(e.message)

2.封装

观察前面的文件发现,除了sql语句及参数不同,其它语句都是一样的。为了方便,我们可以创建MysqlHelper.py文件,定义类,将这些重复性语句进行封装。#encoding=utf8

import pymysql

class MysqlHelper():

#定义初始化函数

def __init__(self,host,port,db,user,passwd,charset='utf8'):

self.host=host

self.port=port

self.db=db

self.user=user

self.passwd=passwd

self.charset=charset

#定义连接函数,用于创建连接对象和游标对象

def connect(self):

self.conn=pymysql.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 get_one(self,sql,params=()):

result=None

try:

self.connect()

self.cursor.execute(sql, params)

result = self.cursor.fetchone()

self.close()

#此处的close()是调用了本类中的close()函数

except Exception, e:

print e.message

return result

#获取多条查询数据

def get_all(self,sql,params=()):

list=()

#定义list为空元组

try:

self.connect()

self.cursor.execute(sql,params)

list=self.cursor.fetchall()

self.close()

except Exception,e:

print e.message

return list

#定义编辑函数,用于对数据库的增删改操作

def __edit(self,sql,params):

count=0

try:

self.connect()

count=self.cursor.execute(sql,params)

self.conn.commit()

self.close()

except Exception,e:

print e.message

return count

def insert(self,sql,params=()):

return self.__edit(sql,params)

def delete(self, sql, params=()):

return self.__edit(sql, params)

def update(self, sql, params=()):

return self.__edit(sql, params)

3.调用封装类完成数据库操作

(1)创建testInsertWrap.py文件,使用封装好的帮助类完成插入操作

#encoding=utf8

from MysqlHelper import *

sql='insert into students(sname,gender) values(%s,%s)'

sname=input("请输入用户名:")

gender=input("请输入性别,1为男,0为女")

params=[sname,bool(gender)]

mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')

count=mysqlHelper.insert(sql,params)

if count==1:

print('ok')

else:

print('error')    (2)创建testGetOneWrap.py文件,使用封装好的帮助类完成查询最新一行数据操作

#encoding=utf8

from MysqlHelper import *

sql='select sname,gender from students order by id desc'

helper=MysqlHelper('localhost',3306,'test1','root','mysql')

one=helper.get_one(sql)

print(one)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码可以改进的地方有: 1. 数据库连接应该使用上下文管理器,以确保在使用完后及时关闭连接。 2. 应该对数据库查询结果进行错误处理,以确保在查询出错时可以及时发现问题。 3. 应该将数据库查询操作封装在一个函数中,便于复用和维护。 4. 应该使用参数查询,以防止 SQL 注入攻击。 5. 可以考虑使用缓存来提高查询效率。 下面是优后的代码: ``` from contextlib import closing import mysql.connector from mysql.connector import errorcode def get_replace_dict(): """查询所有需要修改的字体""" try: config = { 'user': 'root', 'password': '123456', 'host': 'localhost', 'database': 'test' } with closing(mysql.connector.connect(**config)) as cnx: with closing(cnx.cursor()) as cursor: query = "SELECT chgfont, modifont FROM ai_modify_fonts WHERE status = 1" cursor.execute(query) return dict(cursor.fetchall()) except mysql.connector.Error as e: if e.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("用户名或密码错误") elif e.errno == errorcode.ER_BAD_DB_ERROR: print("数据库不存在") else: print("连接数据库失败:", e) def modify_fonts_upd(question): """替换需要修改的字体""" replace_dict = get_replace_dict() for wrong_word, correct_word in replace_dict.items(): question = question.replace(wrong_word, correct_word) return question ``` 这样的代码更加健壮和易于维护。同时,为了进一步提高效率,可以考虑使用缓存来避免每次查询都要访问数据库的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值