node-sqlite3 學習筆記

* 使用sqlite3持久化數據
* 需求:把一個數組中的每一個對象,每一個對象中的屬性,存到xxx.db文件中去,像數據庫同樣的去操做它
* 功能:1. 建立數據庫(數據庫存在的話,那就直接打開)
*            2. 建立一個表(表存在的話就不用建立啦)
*            3. 有了數據庫和表, 最最基礎的功能就是:
*                  插入數據(單個數據插入或者多個並行插入)
*                  更新數據(根據不一樣的條件更新每列數據)
*                  刪除數據(根據不一樣的條件來刪除每列數據)
*                 查詢數據(單個數據查詢,多個數據查詢)node

 安裝: git

npm install sqlite3

/**
 * Created by Sorrow.X on 2017/7/12.
 */
var SQLite3 = require('sqlite3').verbose();

/**
 * 使用sqlite3持久化數據   
 * 需求:把一個數組中的每一個對象,每一個對象中的屬性,存到xxx.db文件中去,像數據庫同樣的去操做它
 * 功能:1. 建立數據庫(數據庫存在的話,那就直接打開)
 *       2. 建立一個表(表存在的話就不用建立啦)
 *       3. 有了數據庫和表, 最最基礎的功能就是:
 *          插入數據(單個數據插入或者多個並行插入)
 *          更新數據(根據不一樣的條件更新每列數據)
 *          刪除數據(根據不一樣的條件來刪除每列數據)
 *          查詢數據(單個數據查詢,多個數據查詢)
 */
class HandleDB {

    constructor(options) {
        this.databaseFile = options && options.databaseFile || `./data/test.db`;    // 數據庫文件(文件路徑+文件名)
        this.tableName = options && options.tableName || `adsTable`;   // 表名

        this.db = null;    // 打開的數據庫對象
    }

    // 鏈接數據庫(不存在就建立,存在則打開)
    connectDataBase() {
        let _self = this;
        return new Promise((resolve, reject) => {
            _self.db = new SQLite3.Database(_self.databaseFile, function(err) {
                if (err) reject(new Error(err));
                resolve('數據庫鏈接成功');
            });
        });
    }

    /**
     * 建立表
     * @param sentence    CREATE TABLE 語句
     * @used
      let sentence = `
       create table if not exists ${this.tableName}(
            begin_time varchar(255),
            create_time varchar(255),
            end_time varchar(255),
            play_id varchar(255),
            postion_id int(50),
            status int(50),
            task_id int(50)
        );`;
     this.createTable(sentence);
     */
    createTable(sentence) {
        let _self = this;
        return new Promise((resolve, reject) => {
            _self.db.exec(sentence, function(err) {
                if (err) reject(new Error(err));
                resolve(`表建立成功 / 已存在,不須要從新建立該表`);
            });
        });
    }

    /**
     * 執行 增  刪  改  查(單個數據查詢或者多個數據查詢)
     * @param sql    sql語句
     * @param param     參數(能夠是數組或者數字或者字符串,根據sql語句來定)
     * @param mode    執行模式, 默認run,執行sql,若是查詢的話,則使用get(單個)all(多個)
     * @returns {Promise}
       @used
       增 : this.sql(`insert into ${this.tableName} (begin_time, create_time, end_time, play_id, postion_id, status, task_id) values(?, ?, ?, ?, ?, ?, ?)`,
                    [obj.begin_time, obj.create_time, obj.end_time, obj.play_id, obj.postion_id, obj.status, obj.task_id]);

       刪 : this.sql(`delete from ${this.tableName} where id = ?`, id);

       改 : this.sql(`update ${this.tableName} set begin_time = ?, status = ? where postion_id = ?`, [begin_timeValue, statusValue, postion_idValue]);

       查 : this.sql(`select * from ${this.tableName} where id = ?`, id, 'get/all');
     */
    sql(sql, param, mode) {
        let _self = this;
        mode = mode == 'all' ? 'all' : mode == 'get' ? 'get' : 'run';
        return new Promise((resolve, reject) => {
            _self.db[mode](sql, param,
                function (err, data) {    // data: Array, Object
                    if (err) {
                        reject(new Error(err));
                    } else {
                        if (data) {
                            resolve(data);    // 返回數據查詢成功的結果
                        } else {
                            resolve('success');    // 提示 增 刪 改 操做成功
                        };
                    };
                }
            );
        });
    }
};

module.exports = HandleDB;

 

// 使用github

// used:
let db = new HandleDB({
    databaseFile: './data/adsbase.db',
    tableName: 'ads'
});

db.connectDataBase().then((result)=>{
    console.log(result);
    // 建立表(若是不存在的話,則建立,存在的話, 不會建立的,可是仍是會執行回調)
    let sentence = `
       create table if not exists ${db.tableName}(
            begin_time varchar(255),
            create_time varchar(255),
            end_time varchar(255),
            play_id varchar(255),
            postion_id int(50),
            status int(50),
            task_id int(50),
            same_day int(50)
        );`;
    return db.createTable(sentence);
}).then((result)=>{
    console.log(result);
    doLogic();
}).catch((err)=>{
    console.error(err);
});

let doLogic = function() {

    //
    db.sql(`insert into ${db.tableName} (begin_time, create_time, end_time, play_id, postion_id, status, task_id, same_day) values(?, ?, ?, ?, ?, ?, ?, ?)`,
        ['2017/7/12', '2017/7/12', '2017/7/12', 102, 3, 0, 11, '2017-7-12']).then((res)=>{
        console.log(res);
    }).catch((err)=>{
        console.log(err);
    });

    // 一次性插入多個數據
    var data = {
        "Body": [
            {
                "begin_time": "1970-01-01 00:00:00",
                "create_time": "2017-07-11",
                "end_time": "",
                "play_id": 17,
                "postion_id": 1,
                "status": 0,
                "task_id": 24
            },
            {
                "begin_time": "1970-01-01 00:00:00",
                "create_time": "2017-07-11",
                "end_time": "",
                "play_id": 18,
                "postion_id": 4,
                "status": 0,
                "task_id": 24
            },
            {
                "begin_time": "1970-01-01 00:00:00",
                "create_time": "2017-07-11",
                "end_time": "",
                "play_id": 19,
                "postion_id": 2,
                "status": 0,
                "task_id": 24
            },
            {
                "begin_time": "1970-01-01 00:00:00",
                "create_time": "2017-07-11",
                "end_time": "",
                "play_id": 20,
                "postion_id": 3,
                "status": 0,
                "task_id": 24
            }
        ],
        "Code": 0,
        "Message": ""
    };
    var arr = data.Body;
    var promises = arr.map(function(obj) {
        return db.sql(`insert into ${db.tableName} (begin_time, create_time, end_time, play_id, postion_id, status, task_id, same_day) values(?, ?, ?, ?, ?, ?, ?, ?)`,
            [obj.begin_time, obj.create_time, obj.end_time, obj.play_id, obj.postion_id, obj.status, obj.task_id, '2017-7-12']);
    });
    Promise.all(promises).then(function (posts) {
        console.log('所有插入完畢', posts)
    }).catch(function(reason){
        console.error(reason);
    });

    //
    db.sql(`delete from ${db.tableName} where same_day = ?`, '2017-7-12').then((res)=>{
        console.log(res);
    }).catch((err)=>{
        console.log(err);
    });

    //
    db.sql(`update ${db.tableName} set task_id = ? where same_day = ?`, [4, '2017-7-12']).then((res)=>{
        console.log(res);
    }).catch((err)=>{
        console.log(err);
    });

    //
    db.sql(`select * from ${db.tableName} where same_day = ?`, '2017-7-12', 'all').then((res)=>{
        console.log(res);
    }).catch((err)=>{
        console.log(err);
    });
};

 

文檔: https://github.com/mapbox/node-sqlite3/wiki/APIsql

sql工具下載: http://www.sqliteexpert.com/數據庫

相關文章
相關標籤/搜索