1. 程式人生 > >sqlite3增刪改查簡單封裝

sqlite3增刪改查簡單封裝

pre 刪除 port 錯誤 lose try cursor sqli sqlite

import sqlite3


class DBTool(object):
    def __init__(self):
        """
        初始化函數,創建數據庫連接
        """
        self.conn = sqlite3.connect(‘test.db‘)
        self.c = self.conn.cursor()

    def executeUpdate(self, sql, ob):
        """
        數據庫的插入、修改函數
        :param sql: 傳入的SQL語句
        :param ob: 傳入數據
        :return: 返回操作數據庫狀態
        """
        try:
            self.c.executemany(sql, ob)
            i = self.conn.total_changes
        except Exception as e:
            print(‘錯誤類型: ‘, e)
            return False
        finally:
            self.conn.commit()
        if i > 0:
            return True
        else:
            return False

    def executeDelete(self, sql, ob):
        """
        操作數據庫數據刪除的函數
        :param sql: 傳入的SQL語句
        :param ob: 傳入數據
        :return: 返回操作數據庫狀態
        """
        try:
            self.c.execute(sql, ob)
            i = self.conn.total_changes
        except Exception as e:
            return False
        finally:
            self.conn.commit()
        if i > 0:
            return True
        else:
            return False

    def executeQuery(self, sql, ob):
        """
        數據庫數據查詢
        :param sql: 傳入的SQL語句
        :param ob: 傳入數據
        :return: 返回操作數據庫狀態
        """
        test = self.c.execute(sql, ob)
        return test

    def close(self):
        """
        關閉數據庫相關連接的函數
        :return:
        """
        self.c.close()
        self.conn.close()


if __name__ == ‘__main__‘:
    db = DBTool()
    print("插入Student信息")
    name = input(‘輸入姓名:‘)
    age = input(‘輸入年齡:‘)
    ob = [(name, age)]
    sql = ‘insert into stu (name, age) values (?,?)‘
    T = db.executeUpdate(sql, ob)
    if T:
        print(‘插入成功!‘)
    else:
        print(‘插入失敗!‘)

    print("通ID修改Student姓名信息")
    sql2 = ‘UPDATE stu set name = ? where ID=?‘
    id = input(‘輸入需要修改的ID:‘)
    name = input(‘輸入修改的Name:‘)
    ob = [(name, id)]
    T = db.executeUpdate(sql2, ob)
    if T:
        print(‘修改成功!‘)
    else:
        print(‘修改失敗!‘)
        
    print("通ID刪除Student信息")
    num = input(‘輸入需要刪除的學員ID:‘)
    sql2 = "DELETE from stu where ID=?"
    ob = [(num)]
    T = db.executeDelete(sql2, ob)
    if T:
        print(‘刪除成功!‘)
    else:
        print(‘刪除失敗!‘)

    print("通姓名查詢Student信息")
    sql = ‘select * from stu where name=?‘
    name = input(‘輸入需要查詢的學員姓名:‘)
    ob = [(name)]
    s = db.executeQuery(sql, ob)
    st = []
    for st in s:
        print(‘ID:‘, st[0], ‘  Name:‘, st[1], ‘  Age:‘, st[2])
    if any(st):
        pass
    else:
        print("輸入有誤,該學員不存在")
    
    # 關閉數據庫連接
    db.close() 

  

sqlite3增刪改查簡單封裝