Nodejs中使用mariadb库连接MySQL数据库

前言

最新写了一个水质同步入库的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兼容。

  • About MariaDB Connector/Node.js
  • Node.js Connector
  • Node.js Connection Options

相关资料

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

https://github.com/mariadb-corporation/mariadb-connector-nodejs/blob/master/documentation/callback-api.md

https://mariadb.com/kb/en/nodejs-connector/

你可能感兴趣的:(NodeJS和Express,Vue学习)