TypeScript封裝統一操作Mysql Mongodb Mssql的底層類庫demo


/*

功能:定義一個操作數據庫的庫  支持 Mysql Mssql  MongoDb

要求1:Mysql MsSql  MongoDb功能一樣  都有 add  update  delete  get方法    

注意:約束統一的規范、以及代碼重用

解決方案:需要約束規范所以要定義接口 ,需要代碼重用所以用到泛型

    1、接口:在面向對象的編程中,接口是一種規范的定義,它定義了行為和動作的規范

    2、泛型 通俗理解:泛型就是解決 類 接口 方法的復用性、


*/

interface DBI<T>{
    add(info:T):boolean;
    update(info:T,id:number):boolean;
    delete(id:number):boolean;
    get(id:number):any[];
}

//定義一個操作mysql數據庫的類       注意:要實現泛型接口 這個類也應該是一個泛型類

class MysqlDb<T> implements DBI<T>{

    constructor(){

        console.log('數據庫建立連接');
    }
    add(info: T): boolean {

        console.log(info);

        return true;
       
    }    
    
    update(info: T, id: number): boolean {
        throw new Error("Method not implemented.");
    }
    delete(id: number): boolean {
        throw new Error("Method not implemented.");
    }
    get(id: number): any[] {
        var list=[

            {
                title:'xxxx',
                desc:'xxxxxxxxxx'
            },
            {
                title:'xxxx',
                desc:'xxxxxxxxxx'
            }
        ]

        return list;
    }
    
}

//定義一個操作mssql數據庫的類  


class MsSqlDb<T> implements DBI<T>{

    constructor(){

        console.log('數據庫建立連接');
    }
    add(info: T): boolean {
        console.log(info);
        return true;
    }    
    update(info: T, id: number): boolean {
        throw new Error("Method not implemented.");
    }
    delete(id: number): boolean {
        throw new Error("Method not implemented.");
    }
    get(id: number): any[] {
       

        var list=[

            {
                title:'xxxx',
                desc:'xxxxxxxxxx'
            },
            {
                title:'xxxx',
                desc:'xxxxxxxxxx'
            }
        ]

        return list;
    }

}

//操作用戶表   定義一個User類和數據表做映射

/*

class User{
    username:string | undefined;
    password:string | undefined;
}


var u=new User();
u.username='張三111';
u.password='123456';


var oMysql=new MysqlDb<User>(); //類作為參數來約束數據傳入的類型 
oMysql.add(u);

*/



class User{
    username:string | undefined;
    password:string | undefined;
}


var u=new User();
u.username='張三2222';
u.password='123456';

var oMssql=new MsSqlDb<User>();
oMssql.add(u);


//獲取User表 ID=4的數據
var data=oMssql.get(4);
console.log(data);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM