我正在使用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�z\u0014NF@' } ]
所有非空字符串都是7或8字节,但最困扰我的是这个示例的第二行,我得到一个空字符串,而我知道MDB中有一个非空数字:这意味着我无法尝试从字符串字节构建数字。
那么,如何在linux节点的MDB文件中读取类型Double
的数字?
我确切地说
答案 0 :(得分: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查询要快。