【问题标题】:node mysql connection pool exports节点mysql连接池导出
【发布时间】:2018-05-13 05:40:53
【问题描述】:

我正在使用 electronjs 制作应用程序。我创建了一个连接池,我将在我的项目中全局使用它。用户可以选择他需要连接的 mysql 服务器,并且选择的服务器配置保存在 lokijs 数据库中。当我们创建连接池时,我们将从 lokijs 数据库中获取 mysql 连接详细信息。

现在我收到这样的错误。

未捕获的类型错误:无法读取属性'find' of null

请看下面的代码

   var mysql = require('mysql');
   var loki = require("lokijs");

var db = new loki('config/config.json', {
    autoload: true,
    autoloadCallback: databaseInitialize,
    autosave: true,
    autosaveInterval: 1000 // save every four seconds for our example
});

function databaseInitialize() {
    // on the first load of (non-existent database), we will have no collections so we can 
    //   detect the absence of our collections and add (and configure) them now.
    var CurConnection = db.getCollection("CurConnection");
    if (CurConnection === null) {
        CurConnection = db.addCollection("CurConnection");
    }
}

var CurConnection = db.getCollection("CurConnection");
var rows = CurConnection.find({
    '$loki': {
        '$eq': 1
    }
});

var row = rows[0];

var servername = row.selservername;
var port = row.selport;
var dbname = row.seldbname;
var username = row.selusername;
var password = row.selpassword;

var connection = mysql.createPool({
    multipleStatements: true,
    host: servername,
    port: port,
    user: username,
    password: password,
    database: dbname
});

module.exports = connection;

【问题讨论】:

  • 我猜db.getCollection("CurConnection");databaseInitialize 之前执行。您可以通过将console.log 放入databaseInitialize db.getCollection 之前进行测试
  • 感谢您的回复。我试过console.log。在控制台中显示错误后将显示该消息。这意味着你说的是正确的。有什么解决办法吗?
  • 你使用了一种叫做惰性评估的东西。简单地说,创建一个函数来获取CurConnection 并创建db connection,然后将此函数导出到其他模块。你还应该monetize这个函数,这样它就不会多次创建相同的连接。

标签: mysql node.js electron lokijs


【解决方案1】:

在这段代码之后添加 2-3 秒的睡眠

var CurConnection = db.getCollection("CurConnection");
if (CurConnection === null) {
    CurConnection = db.addCollection("CurConnection");
}

或在此代码之前

 var rows = CurConnection.find({
    '$loki': {
        '$eq': 1
    }
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 2018-03-14
    • 1970-01-01
    • 2021-01-29
    • 2013-08-20
    • 2020-06-24
    • 2014-01-05
    • 1970-01-01
    相关资源
    最近更新 更多