我正在使用 MDBTools 在 Linux 上的 nodejs 中查询一些 MDB 文件, unixodbc和 node odbc包。
使用这段代码
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 中有一个非空数字:这意味着我不能尝试从字符串字节构建数字。
那么,如何在 Linux Node 的 MDB 文件中读取 Double
类型的数字?
我很确定
- 像 MDBViewer 这样的工具(使用 MDBTools)可以正确读取这些数字
- JavaScript 数字对我来说足够精确:这些数字都适合 float32
- 我不能对 MDB 文件应用冗长的转换:我必须对几百个经常更改的文件进行快速查询......
- 一个我不能真正发出查询但可以让我阅读整个表格的解决方案也是可以接受的
最佳答案
由于我无法让 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 查询更快。
关于javascript - 如何读取 Node 中 MDB 文件中 double 类型的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17991304/