当前位置: 首页 > 软件库 > 数据库相关 > >

node-mysql2

授权协议 MIT License
开发语言 C/C++
所属分类 数据库相关
软件类型 开源软件
地区 不详
投 递 者 秦琦
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Node MySQL 2

MySQL client for Node.js with focus on performance. Supports prepared statements, non-utf8 encodings, binary log protocol, compression, ssl much more

Table of contents

History and Why MySQL2

MySQL2 project is a continuation of MySQL-Native. Protocol parser code was rewritten from scratch and api changed to match popular mysqljs/mysql. MySQL2 team is working together with mysqljs/mysql team to factor out shared code and move it under mysqljs organisation.

MySQL2 is mostly API compatible with mysqljs and supports majority of features. MySQL2 also offers these additional features

Installation

MySQL2 is free from native bindings and can be installed on Linux, Mac OS or Windows without any issues.

npm install --save mysql2

First Query

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);

Using Prepared Statements

With MySQL2 you also get the prepared statements. With prepared statements MySQL doesn't have to prepare plan for same query everytime, this results in better performance. If you don't know why they are important, please check these discussions

MySQL provides execute helper which will prepare and query the statement. You can also manually prepare / unprepare statement with prepare / unprepare methods.

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);

Using connection pools

Connection pools help reduce the time spent connecting to the MySQL server by reusing a previous connection, leaving them open instead of closing when you are done with them.

This improves the latency of queries as you avoid all of the overhead that comes with establishing a new connection.

// get the client
const mysql = require('mysql2');

// Create the connection pool. The pool-specific settings are the defaults
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  database: 'test',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

The pool does not create all connections upfront but creates them on demand until the connection limit is reached.

You can use the pool in the same way as connections (using pool.query() and pool.execute()):

// For pool initialization, see above
pool.query("SELECT field FROM atable", function(err, rows, fields) {
   // Connection is automatically released when query resolves
})

Alternatively, there is also the possibility of manually acquiring a connection from the pool and returning it later:

// For pool initialization, see above
pool.getConnection(function(err, conn) {
   // Do something with the connection
   conn.query(/* ... */);
   // Don't forget to release the connection when finished!
   pool.releaseConnection(conn);
})

Using Promise Wrapper

MySQL2 also support Promise API. Which works very well with ES7 async await.

async function main() {
  // get the client
  const mysql = require('mysql2/promise');
  // create the connection
  const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
  // query database
  const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);
}

MySQL2 use default Promise object available in scope. But you can choose which Promise implementation you want to use

// get the client
const mysql = require('mysql2/promise');

// get the promise implementation, we will use bluebird
const bluebird = require('bluebird');

// create the connection, specify bluebird as Promise
const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test', Promise: bluebird});

// query database
const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);

MySQL2 also exposes a .promise() function on Pools, so you can create a promise/non-promise connections from the same pool

async function main() {
  // get the client
  const mysql = require('mysql2');
  // create the pool
  const pool = mysql.createPool({host:'localhost', user: 'root', database: 'test'});
  // now get a Promise wrapped instance of that pool
  const promisePool = pool.promise();
  // query database using promises
  const [rows,fields] = await promisePool.query("SELECT 1");

MySQL2 exposes a .promise() function on Connections, to "upgrade" an existing non-promise connection to use promise

// get the client
const mysql = require('mysql2');
// create the connection
const con = mysql.createConnection(
  {host:'localhost', user: 'root', database: 'test'}
);
con.promise().query("SELECT 1")
  .then( ([rows,fields]) => {
    console.log(rows);
  })
  .catch(console.log)
  .then( () => con.end());

Array results

If you have two columns with the same name, you might want to get results as an array rather than an object to prevent them from clashing. This is a deviation from the Node MySQL library.

For example: select 1 as foo, 2 as foo.

You can enable this setting at either the connection level (applies to all queries), or at the query level (applies only to that specific query).

Connection Option

const con = mysql.createConnection(
  { host: 'localhost', database: 'test', user: 'root', rowsAsArray: true }
);

Query Option

con.query({ sql: 'select 1 as foo, 2 as foo', rowsAsArray: true }, function(err, results, fields) {
  console.log(results) // will be an array of arrays rather than an array of objects
  console.log(fields) // these are unchanged
});

API and Configuration

MySQL2 is mostly API compatible with Node MySQL. You should check their API documentation to see all available API options.

If you find any incompatibility with Node MySQL, Please report via Issue tracker. We will fix reported incompatibility on priority basis.

Documentation

You can find more detailed documentation here. You should also check various code examples to understand advanced concepts.

Acknowledgements

  • Internal protocol is written by @sidorares MySQL-Native
  • Constants, SQL parameters interpolation, Pooling, ConnectionConfig class taken from node-mysql
  • SSL upgrade code based on @TooTallNate code
  • Secure connection / compressed connection api flags compatible to MariaSQL client.
  • Contributors

Contributing

Want to improve something in node-mysql2. Please check Contributing.md for detailed instruction on how to get started.

 相关资料
  • Node是kubernetes集群的工作节点,可以是物理机也可以是虚拟机。 Node的状态 Node包括如下状态信息: Address HostName:可以被kubelet中的--hostname-override参数替代。 ExternalIP:可以被集群外部路由到的IP地址。 InternalIP:集群内部使用的IP,集群外部无法访问。 Condition OutOfDisk:磁盘空间不足时

  • node 负责 peer node 子命令。

  • 这用于确定进程需要运行的节点的值。 由于分布式编程用于在不同节点上运行函数,因此在希望在不同机器上运行程序时,此功能非常有用。 语法 (Syntax) node() 参数 (Parameters) None 返回值 (Return Value) 这将返回本地节点的名称。 如果节点未分发,则返回nonode@nohost 。 例如 (For example) -module(helloworld)

  • The Po.et Node The Po.et Node allows you to timestamp documents in a decentralized manner. It's built on top of the Bitcoin blockchain and IPFS. Index The Po.et Node Index How to Run the Po.et Node De

  • Node-Lua是一款基于Lua实现的脚本和服务器引擎,它支持构建海量Lua服务(Context_Lua)并以多线程方式运行在多核服务器上,采用了任务多路复用的设计方案,有效利用了多核优势。node-lua致力于构建一个快速、简单易用的Lua脚本和服务器开发和运行环境。该引擎参考了Node-Js和Skynet的设计思想,并对其进行了整合和优化。 该引擎当前版本实现了以下特性: 引擎核心层同时支持同

  • 在程序里经常都需要生成一些特定格式的 id ,每种场合的需求都可能有些不一样,虽然写起来代码不复杂,但零零碎碎的东西做多了也挺烦的,于是设计了这个用于 node.js 的万能 ID 生成器。 AnyID 生成的 ID 为字符串(也可以纯数字),信息密度尽可能的高,也就是用最少的位数表示尽量多的信息。 AnyID 设计的首要考虑原则是 API 的直观易用。看看这些例子: 指定长度,随机值填充 21