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)
總結
以上是生活随笔為你收集整理的mysql 参数化 c_MySQL(16):参数化、封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dockerfile文件名_Linux云
- 下一篇: python葡萄酒数据集_利用pytho