1. 程式人生 > 資料庫 >資料庫學習之將mysql的insert和select操作封裝成類

資料庫學習之將mysql的insert和select操作封裝成類

import pymysql

class MyMysql:
    def __init__(self):
        mysql_config = {
                'host':'127.0.0.1','port':3306,'user':'root','password':'qwe123','db':'wumou','charset': 'utf8'
                }
        self.conn = pymysql.connect(**mysql_config)
        self.cur = self.conn.cursor()

    def insert(self,tbname,*args):
        '''注意在mysql中,insert語句:insert into tbname values(1,'wuhan',14)
            所以在python操作mysql的insert語句時,要注意將value轉換為括號裡面放值
            且整個value為字串型別'''
        args = list(args)
        for i in range(len(args)):
            args[i] = tuple(args[i])
        args = str(args)
        st = args[1:-1]
        sql = f'insert into {tbname} value {st}'
        self.cur.execute(sql)

    def select(self,field,select_var = 1,**condition):
        '''python操作mysql資料庫進行查詢操作
            tbname為表名;select_var預設形參為1時是有一個條件查詢,為2時是無條件查詢,為3是多條件查詢
            condition為條件'''
        if select_var == 1:
            for key,value in condition.items():
                condition_new = f"where {key} = '{value}'"
            sql = f'select {field} from {tbname} {condition_new}'
        elif select_var ==2:
            sql = f'select {field} from {tbname}'
        else:
            a = []          #將條件(字典型別)變為列表型別
            for key,value in condition.items():
                a.extend([key,value])

            b = []          #將每個條件中的欄位與值用=相連
            for i in range(len(a)):
                if i % 2 == 0:
                    b.append(f"{a[i]} = '{a[i+1]}")
            b = str(b)
                            #切出有用的條件語句
            b = b.replace('","'," 'and ")
            print('第二次b  ',b)
            sql = f"select {field} from {tbname} where {b[2:-2]}'"

        self.cur.execute(sql)
        for i in self.cur:
            print(i)
            
            #mysql的update和delete方法主要思路如上!!!
    def update(self):
    	pass
    def delete(self):
    pass


    def close(self):
        self.conn.commit()
        self.conn.close()
        self.cur.close()

m = MyMysql()
# m.insert('student',[8,'吳某',2,54,'third'],[9,'中國',3,57,'first'])
m.select('*','student',select_var=3,name = 'zhongguo',age = 18,gradname = 'first')
m.close()

所操作的mysql表示例:
在這裡插入圖片描述