5

我正在使用MDBToolsunixodbcnode 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�z\u0014NF@' } ]

所有非空字符串都是 7 或 8 个字节,但最困扰我的是这个示例的第二行,我知道 MDB 中有一个非空数字,但我得到一个空字符串:这意味着我无法尝试构建字符串字节中的数字。

那么,如何Double在 Linux 上的节点中读取 MDB 文件中的类型数?

我准确地说

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

1 回答 1

3

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

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' ] ]

令人惊讶的是,这比使用 node-odbc 和 linuxodbc 查询要快。

于 2013-08-01T12:35:27.410 回答