mysql mariadb nodejs_Nodejs中使用mariadb库连接MySQL数据库

前言

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+

Documentation callback-api

本文同步分享在 博客“雪域迷影”(CSDN)。

如有侵权,请联系 support@oschina.cn 删除。

本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值