前言
最新寫了一個水質同步入庫的TypeScript程序,數據庫使用的是MySQL,於是選擇了mariadb這個庫,其npmjs官網地址爲https://www.npmjs.com/package/mariadb,Github倉庫地址爲:https://github.com/mariadb-corporation/mariadb-connector-nodejs
Node.js連接器入門
MariaDB Node.js連接器可通過Node.js存儲庫獲得。 您可以使用npm安裝它:
$ npm install mariadb
在2017之前使用ECMAScript:
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'mydb.com',
user:'myUser',
password: 'myPassword',
connectionLimit: 5
});
pool.getConnection()
.then(conn => {
conn.query("SELECT 1 as val")
.then((rows) => {
console.log(rows); //[ {val: 1}, meta: ... ]
//Table must have been created before
// " CREATE TABLE myTable (id int, val varchar(255)) "
return conn.query("INSERT INTO myTable value (?, ?)", [1, "mariadb"]);
})
.then((res) => {
console.log(res); // { affectedRows: 1, insertId: 1, warningStatus: 0 }
conn.end();
})
.catch(err => {
//handle error
console.log(err);
conn.end();
})
}).catch(err => {
//not connected
});
使用ECMAScript 2017:
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'mydb.com',
user:'myUser',
password: 'myPassword',
connectionLimit: 5
});
async function asyncFunction() {
let conn;
try {
conn = await pool.getConnection();
const rows = await conn.query("SELECT 1 as val");
console.log(rows); //[ {val: 1}, meta: ... ]
const res = await conn.query("INSERT INTO myTable value (?, ?)", [1, "mariadb"]);
console.log(res); // { affectedRows: 1, insertId: 1, warningStatus: 0 }
} catch (err) {
throw err;
} finally {
if (conn) return conn.end();
}
}
MariaDB連接器可以在後端使用不同的API:Promise和Callback。 默認的API是Promise。 提供回調API是爲了與mysql和mysql2 API兼容。
相關資料
MariaDB Node.js connector-MariaDB的npm官網
https://www.npmjs.com/package/mariadb
Non-blocking MariaDB and MySQL client for Node.js.
MariaDB and MySQL client, 100% JavaScript, with TypeScript definition, with the Promise API.
version before 2.4 is compatible with Node.js 6+ version after 2.4 is compatible with Node.js 10+