如何读取节点中MDB文件中类型为doubles的列



我正在使用MDBTools、unixodbc和node-odbc包查询linux上nodejs中的一些MDB文件。

使用此代码

db.query("select my_str_col, my_dbl_col from my_table", function (err, rows) {
    if (err) return console.log(err);
    console.log(rows);
    db.close();
});

我可以查询my_str_col字符串列,但我不能破译my_dbl_col Double列,我得到了这样的东西:

[ { my_str_col: 'bla',     my_dbl_col: '{u0014�Gai�@' },
  { my_str_col: 'bla bla', my_dbl_col: '' },
  { my_str_col: 'bla', my_dbl_col: '�G�zu0014NF@' } ]

所有非空字符串都是7或8个字节,但最让我困扰的是这个例子的第二行,当我知道MDB中有一个非空数字时,我得到了一个空字符串:这意味着我不能尝试从字符串字节构建数字。

那么,如何在linux上的node中读取MDB文件中Double类型的数字呢?

我精确定位

  • 像MDBViewer这样的工具(使用MDBTools)可以正确读取这些数字
  • JavaScript的数字对我来说足够精确:这些数字都可以放在float32中
  • 我不能对MDB文件进行长时间的转换:我必须对几百个经常更改的文件进行快速查询
  • 我不能真正发出查询,但可以读取整个表的解决方案也是可以接受的

由于我无法让node odbc正确地破译数字,我编写了一个函数,调用mdb导出(非常快)并读取整个表。

var fs   = require("fs"),
    spawn  = require('child_process').spawn,
    byline = require('byline'); // npm install byline   
// Streaming reading of choosen columns in a table in a MDB file. 
// parameters :
//   args :
//     path : mdb file complete path
//     table : name of the table
//     columns : names of the desired columns
//   read : a callback accepting a row (an array of strings)
//   done : an optional callback called when everything is finished with an error code or 0 as argument
function queryMdbFile(args, read, done) {
    var cmd = spawn('/usr/bin/mdb-export', [args.path, args.table]);
    var rowIndex = 0, colIndexes;
    byline(cmd.stdout).on('data', function (line) {
        var cells = line.toString().split(',');
        if (!rowIndex++) { // first line, let's find the col indexes
            var lc = function(s){ return s.toLowerCase() };
            colIndexes = args.columns.map(lc).map(function(name) {
                return cells.map(lc).indexOf(name);
            });
        } else { // other lines, let's give to the callback the required cells
            read(colIndexes.map(function(index){ return ~index ? cells[index] : null }));
        }
    });
    cmd.on('exit', function (code) {
        if (done) done(code);
    });
}

下面是一个例子,我用问题的所有行构建了一个数组

var rows = [];
queryMdbFile({
    path: "mydatabase.MDB",
    table: 'my_table',
    columns : ['my_str_col', 'my_dbl_col']
},function(row) {
    rows.push(row);
},function(errorCode) {
    console.log(errorCode ? ('error:'+errorCode) : 'done');
});

所有内容都以字符串形式读取,但很容易解析:

[ ['bla',     '1324'  ],
  ['bla bla', '332e+5'],
  ['bla',     '43138' ] ]

令人惊讶的是,这比使用nodeodbc和linuxodbc进行查询要快。

最新更新