bookshelf and knex bookmark
/*
// target table sql
CREATE TABLE public.company
(
id integer NOT NULL,
name text COLLATE pg_catalog."default" NOT NULL,
age integer NOT NULL,
address character(50) COLLATE pg_catalog."default",
salary real,
CONSTRAINT company_pkey PRIMARY KEY (id)
)
*/
prepare/
/*
$ npm install knex@0.13 --save
$ npm install bookshelf --save
# Then add one of the following:
$ npm install pg
$ npm install mysql
$ npm install mariasql
$ npm install sqlite3
*/
/
console.log("hello bookshelf");
var knex = require('knex')({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'admin',
password : 'admin',
database : 'ABC',
charset : 'utf8'
}
});
var bookshelf = require('bookshelf')(knex);
var myc = bookshelf.Model.extend({
tableName: 'company'
});
query insert update delete
/*
// query 1
myc.where('id', 1).fetch().then(function(my) {
//method 1
var st= JSON.stringify(my);
console.log(st);
var jo=JSON.parse(st);
console.log(" ----- "+jo.address);
// method 2
console.log(" method 2----- "+my.get('address'));
}).catch(function(err) {
console.error(err);
});
*/
// query 2
myc.fetchAll().then(function(my) {
//method 1
var st= JSON.stringify(my);
console.log(st);
var jo=JSON.parse(st);
console.log(" ----- "+jo[0].address);
// method 2
//console.log(" method 2----- "+my[1].get('address'));
}).catch(function(err) {
console.error(err);
});
// insert
new myc({id:7,name:'huaerduoduo',age:30,address:'xian',salary:50})
.save(null, {method: 'insert'})
.then(function(model) {
console.log(" add row successful. ");
});
// update
new myc({id: 5, name: 'huaer'})
.save({address: 'XI\'AN'}, {patch: true})
.then(function(model) {
console.log(" add row successful. ");
});
new myc({id: 6}).destroy().then(
function(model) {
console.log(" delete row successful. ");
}
);
query insert update delete