Home  >  Article  >  Database  >  About node operation mysql database sample code sharing

About node operation mysql database sample code sharing

黄舟
黄舟Original
2017-03-18 14:21:261285browse

This article mainly introduces the node operationmysql database, and combines the example form with a more detailed analysis of the connection, addition, deletion, modification, transaction processing and error handling of the node operation database. For operating skills, friends in need can refer to

. This article describes how node operates mysql database with examples. Share it with everyone for your reference, the details are as follows:

1. Establish a database connection: createConnection(<a href="http://www.php.cn/wiki/60.html" target="_blank">Object</a>)Method

This method accepts an object as a parameter. The object has four commonly used attributes: host, user, password, and database. The same parameters as the database link in php. The attribute list is as follows:

host The host name where the database is connected. (Default: localhost)
port Connection port. (Default: 3306)
localAddress IP address used for TCP connections. (Optional Select)
socketPath The path to link to the unix domain. This parameter will be ignored when using host and port.
user The username of the MySQL user.
password MySQL user’s password.
database The name of the database to link to (optional).
charset Character set for the connection. (Default: 'UTF8_GENERAL_CI'. Use uppercase when setting this value!)
timezone Save local The time zone of the time. (Default: 'local')
stringifyObjects Whether to serialize objects. See issue #501. (Default : 'false')
insecureAuth Whether old authentication methods are allowed to connect to the database instance. (Default: false)
typeCast Determines whether to convert column values ​​to local Javascript type column values. (Default: true)
queryFormat Customized query statement formattingFunction.
supportBigNumbers The database handles large numbers (long integers and decimals), should be enabled (default: false).
bigNumberStrings Enable supportBigNumbers and bigNumberStrings and force these numbers to be returned as strings(default : false).
dateStrings Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings instead of a javascript Date object. (Default: false )
debug Whether debugging is enabled. (Default: false)
multipleStatements is allowed Pass multiple query statements in one query. (Default: false)
flags Link flags.

You can also use string connection database example:

var connection = mysql.createConnection(&#39;mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700&#39;);

2. End the database connection end() and destroy( )

end() accepts a callback function, and will be triggered after the query ends. If there is an error in the query, the link will still be terminated, and the error will be passed to the callback function for processing .

destroy() terminates the database connection immediately. Even if the query is not completed, subsequent callback functions will not be triggered.

3. Create a connection pool createPool(Object) The Object and createConnection parameters are the same.

You can listen to the connection event and set the session value

pool.on(&#39;connection&#39;, function(connection) {
 connection.query(&#39;SET SESSION auto_increment_increment=1&#39;)
});

connection.release() to release the connection to the connection pool. If you need to close the connection and delete it, you need to use connection.destroy()

In addition to accepting the same parameters as connection, pool also accepts several extended parameters

createConnection Function used to create connections. (Default: mysql.createConnection)
waitForConnections Determines when there is no connection pool or number of connections The behavior of the pool when reaching the maximum value. When it is true, the connection will be put into the queue and called when available. When it is false, an error will be returned immediately. (Default: true)
connectionLimit Maximum number of connections. (Default: 10)
queueLimit The maximum length of the connection request in the connection pool. If it exceeds this length, it will Report an error, there is no limit when the value is 0. (Default: 0)

4、连接池集群

允许不同的host链接

// create
var poolCluster = mysql.createPoolCluster();
poolCluster.add(config); // anonymous group
poolCluster.add(&#39;MASTER&#39;, masterConfig);
poolCluster.add(&#39;SLAVE1&#39;, slave1Config);
poolCluster.add(&#39;SLAVE2&#39;, slave2Config);
// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
poolCluster.getConnection(function (err, connection) {});
// Target Group : MASTER, Selector : round-robin
poolCluster.getConnection(&#39;MASTER&#39;, function (err, connection) {});
// Target Group : SLAVE1-2, Selector : order
// If can&#39;t connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)
poolCluster.on(&#39;remove&#39;, function (nodeId) {
   console.log(&#39;REMOVED NODE : &#39; + nodeId); // nodeId = SLAVE1
});
poolCluster.getConnection(&#39;SLAVE*&#39;, &#39;ORDER&#39;, function (err, connection) {});
// of namespace : of(pattern, selector)
poolCluster.of(&#39;*&#39;).getConnection(function (err, connection) {});
var pool = poolCluster.of(&#39;SLAVE*&#39;, &#39;RANDOM&#39;);
pool.getConnection(function (err, connection) {});
pool.getConnection(function (err, connection) {});
// destroy
poolCluster.end();

链接集群的可选参数

canRetry 值为true时,允许连接失败时重试(Default: true)
removeNodeErrorCount 当连接失败时 errorCount 值会增加. 当errorCount 值大于 removeNodeErrorCount 将会从PoolCluster中删除一个节点. (Default: 5)
defaultSelector 默认选择器. (Default: RR)
RR 循环. (Round-Robin)
RANDOM 通过随机函数选择节点.
ORDER 无条件地选择第一个可用节点.

5、切换用户/改变连接状态

Mysql允许在比断开连接的的情况下切换用户

connection.changeUser({user : &#39;john&#39;}, function(err) {
 if (err) throw err;
});

参数

user 新的用户 (默认为早前的一个).
password 新用户的新密码 (默认为早前的一个).
charset 新字符集 (默认为早前的一个).
database 新数据库名称 (默认为早前的一个).

6、处理服务器连接断开

var db_config = {
  host: &#39;localhost&#39;,
  user: &#39;root&#39;,
  password: &#39;&#39;,
  database: &#39;example&#39;
};
var connection;
function handleDisconnect() {
 connection = mysql.createConnection(db_config); // Recreate the connection, since
                         // the old one cannot be reused.
 connection.connect(function(err) {       // The server is either down
  if(err) {                   // or restarting (takes a while sometimes).
   console.log(&#39;error when connecting to db:&#39;, err);
   setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
  }                   // to avoid a hot loop, and to allow our node script to
 });                   // process asynchronous requests in the meantime.
                     // If you&#39;re also serving http, display a 503 error.
 connection.on(&#39;error&#39;, function(err) {
  console.log(&#39;db error&#39;, err);
  if(err.code === &#39;PROTOCOL_CONNECTION_LOST&#39;) { // Connection to the MySQL server is usually
   handleDisconnect();             // lost due to either server restart, or a
  } else {                   // connnection idle timeout (the wait_timeout
   throw err;                 // server variable configures this)
  }
 });
}
handleDisconnect();

7、转义查询值

为了避免SQL注入攻击,需要转义用户提交的数据。可以使用connection.escape() 或者 pool.escape()

例如:

var userId = &#39;some user provided value&#39;;
var sql  = &#39;SELECT * FROM users WHERE id = &#39; + connection.escape(userId);
connection.query(sql, function(err, results) {
   // ...
});

或者使用?作为占位符

connection.query(&#39;SELECT * FROM users WHERE id = ?&#39;, [userId], function(err, results) {
   // ...
});

不同类型值的转换结果

Numbers 不变
Booleans 转换为字符串 'true' / 'false'
Date 对象转换为字符串 'YYYY-mm-dd HH:ii:ss'
Buffers 转换为是6进制字符串
Strings 不变
Arrays => ['a', 'b'] 转换为 'a', 'b'
嵌套数组 [['a', 'b'], ['c', 'd']] 转换为 ('a', 'b'), ('c', 'd')
Objects 转换为 key = 'val' pairs. 嵌套对象转换为字符串.
undefined / null ===> NULL
NaN / Infinity 不变. MySQL 不支持这些值,  除非有工具支持,否则插入这些值会引起错误.

转换实例:

var post = {id: 1, title: &#39;Hello MySQL&#39;};
var query = connection.query(&#39;INSERT INTO posts SET ?&#39;, post, function(err, result) {
   // Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = &#39;Hello MySQL&#39;

或者手动转换

var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL");
console.log(query); // SELECT * FROM posts WHERE title=&#39;Hello MySQL&#39;

8、转换查询标识符

如果不能信任SQL标识符(数据库名、表名、列名),可以使用转换方法mysql.escapeId(identifier);

var sorter = &#39;date&#39;;
var query = &#39;SELECT * FROM posts ORDER BY &#39; + mysql.escapeId(sorter);
console.log(query); // SELECT * FROM posts ORDER BY `date`

支持转义多个

var sorter = &#39;date&#39;;
var query = &#39;SELECT * FROM posts ORDER BY &#39; + mysql.escapeId(&#39;posts.&#39; + sorter);
console.log(query); // SELECT * FROM posts ORDER BY `posts`.`date`

可以使用??作为标识符的占位符

var userId = 1;
var columns = [&#39;username&#39;, &#39;email&#39;];
var query = connection.query(&#39;SELECT ?? FROM ?? WHERE id = ?&#39;, [columns, &#39;users&#39;, userId], function(err, results) {
   // ...
});
console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1

9、准备查询

可以使用mysql.format来准备查询语句,该函数会自动的选择合适的方法转义参数。

var sql = "SELECT * FROM ?? WHERE ?? = ?";
var inserts = [&#39;users&#39;, &#39;id&#39;, userId];
sql = mysql.format(sql, inserts);

10、自定义格式化函数

connection.config.queryFormat = function (query, values) {
   if (!values) return query;
   return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
     return this.escape(values[key]);
    }
    return txt;
   }.bind(this));
};
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });

11、获取插入行的id

当使用自增主键时获取插入行id,如:

connection.query(&#39;INSERT INTO posts SET ?&#39;, {title: &#39;test&#39;}, function(err, result) {
   if (err) throw err;
   console.log(result.insertId);
  });

12、流处理

有时你希望选择大量的行并且希望在数据到达时就处理他们,你就可以使用这个方法

var query = connection.query(&#39;SELECT * FROM posts&#39;);
  query
   .on(&#39;error&#39;, function(err) {
    // Handle error, an &#39;end&#39; event will be emitted after this as well
   })
   .on(&#39;fields&#39;, function(fields) {
    // the field packets for the rows to follow
   })
   .on(&#39;result&#39;, function(row) {
    // Pausing the connnection is useful if your processing involves I/O
    connection.pause();
    processRow(row, function() {
     connection.resume();
    });
   })
   .on(&#39;end&#39;, function() {
    // all rows have been received
   });

13、混合查询语句(多语句查询)

因为混合查询容易被SQL注入攻击,默认是不允许的,可以使用:

var connection = mysql.createConnection({multipleStatements: true});

开启该功能。

混合查询实例:

connection.query(&#39;SELECT 1; SELECT 2&#39;, function(err, results) {
   if (err) throw err;
   // `results` is an array with one element for every statement in the query:
   console.log(results[0]); // [{1: 1}]
   console.log(results[1]); // [{2: 2}]
  });

同样可以使用流处理混合查询结果:

var query = connection.query(&#39;SELECT 1; SELECT 2&#39;);
  query
   .on(&#39;fields&#39;, function(fields, index) {
    // the fields for the result rows that follow
   })
   .on(&#39;result&#39;, function(row, index) {
    // index refers to the statement this result belongs to (starts at 0)
   });

如果其中一个查询语句出错,Error对象会包含err.index指示错误语句的id,整个查询也会终止。

混合查询结果的流处理方式是做实验性的,不稳定。

14、事务处理

connection级别的简单事务处理

connection.beginTransaction(function(err) {
   if (err) { throw err; }
   connection.query(&#39;INSERT INTO posts SET title=?&#39;, title, function(err, result) {
    if (err) {
     connection.rollback(function() {
      throw err;
     });
    }
    var log = &#39;Post &#39; + result.insertId + &#39; added&#39;;
    connection.query(&#39;INSERT INTO log SET data=?&#39;, log, function(err, result) {
     if (err) {
      connection.rollback(function() {
       throw err;
      });
     }
     connection.commit(function(err) {
      if (err) {
       connection.rollback(function() {
        throw err;
       });
      }
      console.log(&#39;success!&#39;);
     });
    });
   });
  });

15、错误处理

err.code = string
err.fatal => boolean

The above is the detailed content of About node operation mysql database sample code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn