sqlite3 nodejs封装

    var sqlite3 = require('sqlite3').verbose();
    let dbName = 'my.sqlite';
    var db = new sqlite3.Database(dbName);
    
    db.serialize(() => {
    	let sql = `CREATE TABLE IF NOT EXISTS articles 
    					(id integer primary key, title, content TEXT)
    				`;
    	db.run(sql);
    });
    
    
    class Article {
    
    	constructor(){
    		console.log('------------begin----------');
    	}
    	
    	static all(cb){
    		db.all(`SELECT * FROM articles`, cb);
    	}
    
    	static find(id, cb){
    		db.get(`SELECT * FROM articles WHERE id = ? `, id, cb);
    	}
    
    	static create(data, cb) {
    		const sql = `INSERT INTO articles (title, content) VALUES (?, ?) `;
    		db.run(sql, data.title, data.content, cb);
    	}
    
    	static delete(id, cb){
    		if (!id) return cb(new Error('请输入id'));
    		db.run(`DELETE FROM articles WHERE id = ?`, id, cb);
    	}
    
    }
    
    
    let data = {
    	title: 'Nodejs 实战进阶dasdas',
    	content: 'nodejs dassdasdsa....'
    }
    
    /**
     * [创建数据]
     * @param  {[type]} data  [description]
     * @param  {[type]} (err, data          [description]
     * @return {[type]}       [description]
     */
    Article.create(data, (err, data) => {
    	if(!err) console.log(data);
    });
    
    /**
     * [查询所有数据]
     * @param  {[type]} (err,data [description]
     * @return {[type]}           [description]
     */
    Article.all((err,data) => {
    	console.log(data);
    });
    
    /**
     * [根据条件查询数据]
     * @param  {[type]} 3         [description]
     * @param  {[type]} (err,data [description]
     * @return {[type]}           [description]
     */
    Article.find(3, (err,data) => {
    	if(!err) console.log(data);
    });
    
    /**
     * [删除符合条件的数据]
     * @param  {[type]} 2         [description]
     * @param  {[type]} (err,data [description]
     * @return {[type]}           [description]
     */
    Article.delete(2, (err,data) => {
    	if(!err) console.log('del success');
    });



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值