nodejs到mysql连接错误

时间:2016-04-28 06:19:46

标签: mysql node.js

我收到错误: 错误:错误:握手不活动超时

3 个答案:

答案 0 :(得分:0)

您可以使用node-mysql,它非常易于使用。我曾经使用过一次,这是一个例子: -

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

connection.connect();

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) throw err;
  console.log('The solution is: ', rows[0].solution);
});

connection.end();

答案 1 :(得分:0)

使用连接池:

var mysql = require('mysql');
var pool  = mysql.createPool({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});

pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query( 'SELECT something FROM sometable', function(err, rows) {
    // And done with the connection.
    connection.release();

    // Don't use the connection here, it has been returned to the pool.
  });
});

答案 2 :(得分:0)

我这样将mysql连接到节点。

安装mysql

npm安装mysql

var mysql = require('mysql');

let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    port: '8888',  /* port on which phpmyadmin run */
    password: 'root',
    database: 'dbname',
    socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock' //for mac and linux
});

connection.connect(function(err) {
    if (err) {
      return console.error('error: ' + err.message);
    }

    console.log('Connected to the MySQL server.');
  });