Node.js + mysql:UPDATE查询没有连接

时间:2017-04-08 13:54:12

标签: mysql node.js

我试图在MySQL数据库表上为项目生成假名。因此,当我在表上执行select查询以便知道我的假名称生成循环的行数时,一切正常。但是当我尝试进行实际的更新查询时,我不知道它为什么不起作用。在查询出现之前和之后,我确实将循环作为我的console.log工作,但看起来它甚至在查询更新时都没有尝试连接到数据库。

以下是我的client.js和index.js - >

client.js

'use strict';

/**
 * Module dependencies.
 */

const mysql = require('mysql');
const debug = require('debug')('db');

/**
 * Export the MySQL client pre-handler.
 */

module.exports = {
  assign: 'client',
  method: (request, reply) => {
    debug('Connecting the database')
    const client = mysql.createConnection({
      user: 'root',
      password: 'root',
      socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock', // Replaces host and port
      database: 'db'
    });
    client.connect(function(err) {
      if (err) {
        console.error('Error Connecting: ' + err.stack);
        return;
      }
      console.log('Connected as ID ' + client.threadId);
    });

    return reply(client);
  }
};

index.js

'use strict';

/**
 * Module dependencies.
 */

const os = require('os');
const joi = require('joi');
const debug = require('debug')('server');
const faker = require('faker');

/**
 * New Hapi server
 * (HTTP connection).
 */

debug('New HTTP server');
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({
  host: 'localhost',
  port: 1337,
  routes: {
    cors: true
  }
});

/**
 * Fakes data.
 */

server.route({
  method: 'PUT',
  path: '/faker',
  config: {
    validate: {

    },
    pre: [
      require('./client')
    ]
  },
  handler: (request, response) => {
    let nb_rows;
    let firstname;
    let lastname;
    request.pre.client.query('SELECT COUNT(*) as rows FROM clients', function (error, results, fields) {
      if (error) throw error;
      let nb_rows = results[0].rows;
      for(let i = 1; i <= nb_rows ;i++) {
        let firstname = faker.name.firstName();
        let lastname = faker.name.lastName();
        console.log(firstname);
        request.pre.client.query('UPDATE clients SET firstname = ?, lastname = ? WHERE ID = ?', [firstname, lastname, i], function (error, results, fields) {
          if (error) throw error;
          console.log("HHHEEEEEEEEEEEEEEEYYYYYYYYYY");
        });
        console.log(i);
      };
    });
  }
});

/**
 * Start the server.
 */

debug('Start the HTTP server');
server.start(err => {
  if (err) {
    throw new Error(err)
  }

  console.log(`Server running at ${server.info.uri}`);
});

我花了很多时间寻找答案,而且我在node.js / mysql更新问题上看到了很多已发布的帖子。但我找不到任何匹配的矿井,或者我可能没有理解它。

如果您有任何想法,那将非常感激。

感谢。

0 个答案:

没有答案