Simplify the use of MySQL
Using npm:
$ npm install lia-mysql
import {MysqlInstaller,MysqlConfig} from "core-mysql";
const TARGET = {SQL: {}};
const config = {
host: "127.0.0.1",
port: 3306,
user: "root",
password: "root12345",
database: "test"
}
const installer = new MysqlInstaller(config as MysqlConfig,TARGET,'sys|info');
await installer.load();
const result = await TARGET.SQL.query('select * from users where id=?', [100])
console.log(result);
const row = {
name: 'fengmk2',
otherField: 'other field value',
};
const result = await TARGET.SQL.insert('table-name', row);
console.log(result);
- Insert multi rows
const rows = [{
name: 'fengmk2',
otherField: 'other field value',
}, {
name: 'fengmk3',
otherField: 'other field value',
}];
const result = await TARGET.SQL.insert('table-name', rows);
console.log(result);
- Update a row with primary key:
id
const row = {
id: 123,
name: 'fengmk2',
otherField: 'other field value',
};
const result = await TARGET.SQL.update('table-name', row);
console.log(result);
- Update a row with
options.where
andoptions.columns
const row = {
name: 'fengmk2',
otherField: 'other field value',
};
const result = await TARGET.SQL.update('table-name', row, {
where: { name: row.name },
columns: [ 'otherField' ]
});
console.log(result);
- Update multiple rows with primary key:
id
const options = [{
id: 123,
name: 'fengmk2',
email: 'm@fengmk2.com',
otherField: 'other field value',
}, {
id: 124,
name: 'fengmk2_2',
email: 'm@fengmk2_2.com',
otherField: 'other field value 2',
}]
const result = await TARGET.SQL.updateRows('table-name', options);
console.log(result);
- Update multiple rows with
row
andwhere
properties
const options = [{
row: {
email: 'm@fengmk2.com',
otherField: 'other field value',
},
where: {
id: 123,
name: 'fengmk2',
}
}, {
row: {
email: 'm@fengmk2_2.com',
otherField: 'other field value2',
},
where: {
id: 124,
name: 'fengmk2_2',
}
}]
const result = await TARGET.SQL.updateRows('table-name', options);
console.log(result);
- Get a row
const row = await TARGET.SQL.get('table-name', { name: 'fengmk2' });
=> SELECT * FROM `table-name` WHERE `name` = 'fengmk2'
import {MysqlInstaller,MysqlConfig,MysqlConfigs} from "core-installer";
const TARGET = {SQL: {}};
const config = {
APP1:{
host: "127.0.0.1",
port: 3306,
user: "root",
password: "root12345",
database: "test"
}
}
const installer = new MysqlInstaller(config as MysqlConfigs<MysqlConfig>,TARGET,'sys|info');
await installer.load();
The multi-instance mode is basically the same as the single-instance mode, except that the database instance needs to be specified on the SQL instance, for example:
const result = await TARGET.SQL.APP1.query('select * from users where id=?', [100])
console.log(result);
For other operations, please refer to the single mode