1. 程式人生 > >SQL語句引數化__封裝

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函式裡面了
  • 執行:

這裡寫圖片描述

  • 呼叫cha_all方法:
from sqlcanshuhua import *
xtz = MysqlHelper(user='root',passwd='123',db='test')
sql = 'SELECT * FROM students'
xtz.cha_all(sql)
  • 執行:
    這裡寫圖片描述