SQL語句引數化 封裝

2021-08-11 03:57:21 字數 1806 閱讀 1832

封裝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

defopen

(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()

defclose

(self):

self.cursor.close()

self.conn.close()

defcud(self,sql,params):

#增加、修改、刪除

try:

self.open()

self.cursor.execute(sql,params)

self.conn.commit()

print('ok')

self.close()

except exception as e:

print(e)

defcha_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)

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)插入資料

webform1.aspx imports system.text public class webform1 inherits system.web.ui.page region web 窗體設計器生成的 該呼叫是 web 窗體設計器所必需的。private sub initializecompo...

使用引數化SQL語句進行模糊查詢

今天想用引數化sql語句進行模糊查詢,一開始的使用方法不正確,摸索了好一會。1 使用引數化sql語句進行模糊查詢的正確方法 定義sql語句 string sql select studentid,studentno,studentname from student where studentname...

使用引數化SQL語句進行模糊查詢

今天想用引數化sql語句進行模糊查詢,一開始的使用方法不正確,摸索了好一會。1 使用引數化sql語句進行模糊查詢的正確方法 定義sql語句 string sql select studentid,studentno,studentname from student where studentname...