C/C++教程

一个typescript版本的dao(数据库访问)层的封装

本文主要是介绍一个typescript版本的dao(数据库访问)层的封装,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

首先学会使用mustache语法

select * from {{key1}}字符中{{key1}}会进行匹配map中的key
例如:

    let sql = select * from {{key1}};
    let tableMapper = {
        "key1": "course",
    }
    let result = mustache.render(sql, tableMapper);
    console.log('result:', result);

此段代码中select * from {{key1}}会被替换为select * from course

对mysql的dao层的封装dbmysql.ts

let mysql = require('mysql2');
let mustache = require('mustache');

module.exports = class dbmysql {
    private mysqlConnectPool: any;
    private tableMapper = {
        "key1": "course",
    }
    init(dbConfig: any): void {
        try {
            this.mysqlConnectPool = mysql.createPool(dbConfig);
            console.debug('MySql Adapter Pool generated successfully');
        } catch (error) {
            console.error('[mysql.connector][init][Error]: ', error);
            throw new Error('failed to initialized pool');
        }
    }
    executeQuery(sql: any, params: any): any {
        return new Promise((resolve, reject) => {
            this.mysqlConnectPool.getConnection(function (err: any, conn: any) {
                if (err) {
                    reject(err);
                } else {
                    conn.release();
                    conn.execute(sql, params, function (err: any, rows: any) {
                        if (err) {
                            reject(err);
                        } else {
                            resolve(rows);
                        }
                    });
                }
            });
        });
    }
    // 查找this.tableMapper键匹配表名
    renderQuery(sql: any, params?: any): any {
        sql = mustache.render(sql, this.tableMapper);
        return this.executeQuery(sql, params);
    }
}
这篇关于一个typescript版本的dao(数据库访问)层的封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!