【问题标题】:Nothing happens when I connect to my DB当我连接到我的数据库时没有任何反应
【发布时间】:2018-01-30 10:10:58
【问题描述】:

你能解释一下吗?

我最近一直在研究一些 node.js 的东西来学习它,以便构建一个 DB 接口。我已经能够执行这种con.on() 很多时间没有麻烦。但是在这里,我很困惑。

var mysql = require('mysql');
var prompt = require('prompt');
var con = mysql.createConnection({
    host: "blabla",
    user: "bla",
    password: "bla",
    database: "blabla"
});

var schema_select = {
  properties: {
    select: {
      description: 'what you wanna select bro? :'

    },
    from: {
      description: 'from where bro ? :'
    },
    ask_where: {
      description: 'do you wanna add where ? Y/N :'
    },
    where: {
      description: 'say where then :',
      ask: function() {
        // only ask for WHERE option if user answered Y to ask_where question
        return prompt.history('ask_where').value == 'Y';
      }
    }
  }
};

con.on('error', function(err) {
    if (err) throw err;
    console.log("[mysql error]",err);
    console.log("Connected!");

    prompt.get(schema_select, function (err, result) {
        //
        // Log the results.
        //
        console.log('Command-line input received:');
        var sql_request_where = '';
        if (result.ask_where == 'Y'){
            sql_request_where = 'WHERE ' + result.where;
        }
        var sql_request = 'SELECT ' + result.select + ' FROM ' + result.from;
        con.query(sql_request, function (err, req_result) {
            console.log(req_result);
            console.log("[mysql error]",err);
        })
    });
});

当我在控制台上执行这段代码时,它基本上什么都不做,没有错误,没有日志,什么都没有。 当我尝试在con.on() 之外添加一些随机的console.log('blabla') 时,调用它可以工作,但似乎我什至没有输入con.on()...

C:\Users\flami\Desktop>node first.js

C:\Users\flami\Desktop>

谢谢!

【问题讨论】:

  • 你的.on 只响应一个错误,因为它说con.on('error', ..... ),这意味着on error, do something。由于没有错误,它不会做任何事情。也许查看文档并查看您必须为on connect 处理哪个事件。我假设它是con.on('connect'con.on('connection'
  • 对不起,我在骂你吗?
  • @mitoufle 假设 *$ù%ù 是一个 "beep" 字,那么您的问题标题不合适。
  • 好吧,我的错,谢谢

标签: javascript mysql node.js


【解决方案1】:

根据包自述文件 (https://github.com/mysqljs/mysql) 你必须这样做 con.connect()

con.connect(callback) 接受回调:https://github.com/mysqljs/mysql#establishing-connections

【讨论】:

    【解决方案2】:

    您的 con.on 只处理错误。当它成功时(触发 on('connect'))你不处理它,因此程序认为一切都完成了;并退出;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多