Git Product home page Git Product logo

node-adodb's Introduction

node-adodb

一个用 Node.js 实现的 windows 上的 ADODB 协议。

NPM Version Download Status Windows Status Test Coverage Node Version Dependencies

安装

NPM

使用示例:

ES6
'use strict';

const ADODB = require('node-adodb');
const connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=node-adodb.mdb;');

// 交易
connection
  .transaction([`INSERT INTO Users(UserId, UserName, UserSex, UserBirthday, UserMarried) VALUES (10, "Tom", "Male", "1981/5/10", 0);`,
          `INSERT INTO Users(UserId, UserName, UserSex, UserBirthday, UserMarried) VALUES (11, "Brenda", "Female", "2001/1/11", 0);`,
          `INSERT INTO Users(UserId, UserName, UserSex, UserBirthday, UserMarried) VALUES (10, "Bill", "Male", "1991/3/9", 0);`])
  .then(data => {
    console.log("我们不会到达,因为生成了重复的ID。遇到错误时,请勿插入任何记录。");
  })
  .catch(error => {
    console.error(error);
  });

// 不带返回的执行
connection
  .execute('INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Newton", "Male", 25)')
  .then(data => {
    console.log(JSON.stringify(data, null, 2));
  })
  .catch(error => {
    console.error(error);
  });

// 带返回标识的执行
connection
  .execute('INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Newton", "Male", 25)', 'SELECT @@Identity AS id')
  .then(data => {
    console.log(JSON.stringify(data, null, 2));
  })
  .catch(error => {
    console.error(error);
  });

// 带返回的查询
connection
  .query('SELECT * FROM Users')
  .then(data => {
    console.log(JSON.stringify(data, null, 2));
  })
  .catch(error => {
    console.error(error);
  });

// 带字段描述的查询
connection
  .schema(20)
  .then(schema => {
    console.log(JSON.stringify(schema, null, 2));
  })
  .catch(error => {
    console.error(error);
  });
ES7 async/await
'use strict';

const ADODB = require('node-adodb');
const connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=node-adodb.mdb;');

async function query() {
  try {
    const users = await connection.query('SELECT * FROM Users');

    console.log(JSON.stringify(users, null, 2));
  } catch (error) {
    console.error(error);
  }
}

query();

接口文档:

ADODB.open(connection[, x64]): ADODB

初始化数据库链接参数。

ADODB.query(sql): Promise

执行有返回值的 SQL 语句。

ADODB.execute(sql[, scalar]): Promise

执行无返回值或者带更新统计的的 SQL 语句。

ADODB.transaction(sql[]): Promise

执行多个SQL语句作为事务。

ADODB.schema(type[, criteria][, id]): Promise

查询数据库架构信息。参考: OpenSchema

调试:

设置环境变量 DEBUG=ADODB。参考: debug

扩展:

该类库理论支持 Windows 平台下所有支持 ADODB 连接的数据库,只需要更改数据库连接字符串即可实现操作!

数据库连接字符串:

  • Access 2000-2003 (*.mdb): Provider=Microsoft.Jet.OLEDB.4.0;Data Source=node-adodb.mdb;
  • Access > 2007 (*.accdb): Provider=Microsoft.ACE.OLEDB.12.0;Data Source=adodb.accdb;Persist Security Info=False; 或者   Provider=Microsoft.ACE.OLEDB.15.0;Data Source=adodb.accdb;Persist Security Info=False;

注意:

该类库需要系统支持 Microsoft.Jet.OLEDB.4.0 或者 Microsoft.ACE.OLEDB.12.0,对于 Windows XP SP2 以上系统默认支持 Microsoft.Jet.OLEDB.4.0,其它需要自己安装支持!

推荐使用 Microsoft.ACE.OLEDB.12.0,获取地址: Microsoft.ACE.OLEDB.12.0

Electron

如果你想在 ASAR 包中运行这个模块,你需要做一些修改。

  1. asar 包中排除 adodb.js(使用 electron-builder, 可以配置 extraResources 将制定文件排除在外)
"extraResources": [
  {
    "from": "./node_modules/node-adodb/lib/adodb.js",
    "to": "adodb.js"
  }
]
  1. 告诉 asar 从哪里运行 adodb.js (可以将配置写在 Electronmain.js 文件中)
// Are we running from inside an asar package ?
if (process.mainModule.filename.indexOf('app.asar') !== -1) {
  // In that case we need to set the correct path to adodb.js
  ADODB.PATH = './resources/adodb.js';
}

node-adodb's People

Contributors

deathgrindfreak avatar dependabot-support avatar javiquero avatar nuintun avatar pellejacobs avatar thekeithstewart avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-adodb's Issues

Unexpected end of JSON input

I'm running node-adodb on electronjs with angular-cli, this is my code

   import * as nodeAdodb from 'node-adodb';
    .
    .
    let _p = path.resolve(this.fileImport);
    nodeAdodb.debug = true;
    const connection = nodeAdodb.open(`Provider=Microsoft.Jet.OLEDB.4.0;Data Source=${_p};`);
      connection
        .query('SELECT * FROM M_SUMFUND')
        .on('done', (data: any) => {
          console.log('success');
          console.log(data.records[0]);
        })
        .on('fail', (error: any) => {
          console.log(error);
        });

this is error on electron console:

2017-02-21_121023

Promisification

Hi,

I'm trying to promisify node-adodb using bluebirdjs.

I've tried this:

import Promise from 'bluebird'
import ADODB from 'node-adodb'

const db = ADODB.open(`...`)
const dbQuery = db.query(`...`)
const dbQueryOn = Promise.promisify(dbQuery.on, { context: dbQuery })

dbQueryOn('done').then(data => {
  console.log('data =', data)
}).catch(err => {
  console.log('err =', err)
})

The data is returned, but it comes via the .catch() not the .then() method.

How do I get node-adodb working with promises..?

query a 'Date/Time' column is not working

Hi,

if my table includes a date/time column type then this column is not displayed at the query results. What can I do? (using a Microsoft Access Database - .mdb)

Thanks

Toni

unknown error

Hi Nuitun and thanks for this great job,

I develop an node webkit JS application with MS Access. It worked very well, no problem. But recently, I have an error message that I don't understand :

const ADODB = require('node-adodb');
const connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Test\data.mdb;Jet OLEDB:Database Password=password');

connection
.query("select * from t_users where login='"+login.replace(/'/g,"''")+"' and password = '"+pwd.replace(/'/g,"''")+"'")
.then(data => {
if (data!=undefined && data.length!=0) session = data[0];
})
.catch(error => {
displayWarning(error);
});

error : 牅敲牵䌠捓楲瑰›❌捡詣⁳₅楗摮睯⁳捓楲瑰䠠獯⁴獥⁴艤慳瑣癩₂畳⁲散瑴⁥慭档湩⹥䌠湯慴瑣穥瘠瑯敲愠浤湩獩牴瑡略⁲祳瑳涊⁥潰牵瀠畬⁳❤湩潦浲瑡潩獮മ.

Do you know what it could be please?

unable to fetch date column from ms access db

as per subject line enable to capture date column also enable to perform MAX MIN etc. operation in select query.

I am using "version": "2.0.2"
my date column (column name - AcctDate and table name - AccountingLog) date format is - *1/2/1970 3:46:25 PM *
my query is - SELECT MAX(AccountingLog.AcctDate) FROM AccountingLog WHERE AccountingLog.UserId = "'+userID+'"'
i also tried this query aslo - SELECT * FROM AccountingLog

using above queries enable to capture date column.

Thanks in advance.

Using node-adodb to run a mdb query with query parameters

Hi,
Thanks for making this project available. I am using it in Node to access a MS Access mdb. Currently I cannot see any way of running queries stored in the mdb which have parameters set.
Example:

qUser=
PARAMETERS TEST Long;
SELECT * FROM USERS WHERE ID=[TEST];

In node, if i use connection.query('SELECT * FROM qUser'), then it will return Error{"valid": false,"message":"Operation is not allowed when the object is closed"}
Is there a way to set the parameter from node?
Thanks
Charles

Limitations on packaging for use with Electron JS

In development with Electron JS works perfectly. But after being packaged with .asar format it stops working completely. There are certain limitations: https://github.com/electron/electron/blob/master/docs/tutorial/application-packaging.md#limitations-of-the-node-api .

In 'lib': https://github.com/nuintun/node-adodb/blob/master/lib/proxy.js, there is a call to .spawn process. Is there a way to change this process to one accepted by Electron with .asar? I'm dealing with execFile, comment results. Maybe it could be something else I'm missing out on

image

Operation is not allowed

I keep getting an Error message stating "Operation is not allowed when the object is closed". Any info on this error would be helpful.

var conn = ADODB.open('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=SampleDB.accdb;Persist Security Info=False;');
conn.query('SELECT Control_Number FROM [orders]')
  .on('done', function(data) {
    console.log('done');
    console.log(JSON.stringify(data));
  })
  .on('fail', function(data) {

  });

No way to close a connection after data query

At the moment there is no way to close the connection to the database after you have queried it.

This causes the following error to be returned when attempting to query:

The database has been placed in a state by user 'Admin' on machine 'STRIKER' that prevents it from     being opened or locked.

character encoding

in process.js, the encoding table is set to 'gbk' - which is for traditional Chinese.

the iconv-lite plugin on which node-adodb relies supports many other character sets (Like 'iso-8859-15' which my access DB uses)

It would be great if the encoding wasn't hard-coded but could be given as (optional) parameter when initializing the plugin.

It doesn't returning date into JSON

Hi, I have a MBD table with 8 fields, two of them are DateTime Type, one of them are called "datainformada", but when I made a bellow query, my res.send shows a blank JSON.

var sql = "select datainformada from observacao"

       DAO
           .query(sql)
           .on('done', function(data){
               res.send(data);
           })
           .on('fail', function(error){
               res.send(error);
           })`

When I made query with * to show me all fields, only DateTime types fields doesn't show.

Someone could help me?

connection.query does not return

Hi,

I developed an Angular 4+Electron application with node-adodb. It works perfectly in development mode, but when packaging everything (create the .exe and other electron files), the connection.query does not go to the 'then()' or the 'catch()'!

Using node-adodb version 4.0.6
Angular 4.3.6
electron 1.7.9
electron-packager: 10.1.1

main.js code

const ADODB = require('node-adodb');
const dbProvider = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=';
const databasePath = path.normalize('C:\\temp\\mydb.mdb');

ipcMain.on('select', (event, type, sql) => {

    const reply = 'reply-select-' + type;

    connection = ADODB.open(dbProvider + databasePath + ";");

    connection
      .query(sql)
      .then((data) => {
        event.sender.send(reply, { status: 0, message: '', data: data });
      })
      .catch((error) => {
        console.error('ERROR with select: ' + error);
        event.sender.send(reply, { status: 1, message: error.message, data: {} });
      });
  });

I know it enters in the ipcMain.on, execute the ADODB.open, but after, nothing.

Any clue why or some things that you could suggest me to try?

Thanks

Error: Arguments are of the wrong type, are out of acceptable range

Hi Nuitun,

I tried the adodb on windows with an MsAccess mdb file and I got the following errors.
Do you know what it could be?

const ADODB = require('node-adodb');
const connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=att3000.mdb;');

async function query() {
try {
console.log('go!');
const users = await connection.query('SELECT * FROM userinfo');

console.log(JSON.stringify(users, null, 2));

} catch (error) {
console.error(error);
}
}
query();

Error: Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
at Socket.stdio.stderr.on.data (C:\axe\node_modules\node-adodb\lib\proxy.js:50:14)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:264:12)
at readableAddChunk (_stream_readable.js:251:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at Pipe.onread (net.js:587:20)

Wildcard in node-adodb query returns blank results, but runs OK in MS Access

Everything is working fine for normal SELECT queries, and for SELECT queries with a static WHERE clause (eg: ...WHERE Customer id=1 " works fine! )

HOWEVER, When I use a wildcard * in my WHERE clause as above, I receive an empty dataset:
[]
...Even though the exact same query runs perfectly in MS Access GUI

EG: DB_QUERY("SELECT * FROM Customers WHERE ContactFirstName LIKE '*Howard*' ", req, res, next); returns: [] when running in code, but, the SQL statement run in MS Access returns many records:
Screenshot

Here is my code:

//example of wildcard query

'use strict';
module.exports = (req, res, next) => {
    return DB_QUERY("SELECT * FROM Customers WHERE ContactFirstName LIKE '*Howard*' ", req, res, next);
};

//index.js file


const adodb = require('node-adodb');
const restify = require('restify');
require('restify').plugins;

server.use(restify.plugins.queryParser({ mapParams: true }));
server.use(restify.plugins.bodyParser({ mapParams: true }));
server.use(restify.plugins.acceptParser(server.acceptable));

var DB_PATH = 'C:\\data\\data.mdb';
var ADODB = adodb.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + DB_PATH);
var DB_QUERY = function(dbQuery, req, res, next, pics){
    var isWin = /^win/.test(process.platform);
    if(!isWin){
      res.send('This should be run on a Windows Machine only to connect to Access DB File at: ' + DB_PATH);
    } else {
        try {
            if (fs.existsSync(DB_PATH)) {
            ADODB.query(dbQuery, true)
            .on('done', function(data) {
                console.log(dbQuery.cyan);
                // console.log('data',data); // why is this empty when i run a wildcard search query???
                res.send(data);
            })
            .on('fail', function(error) {
                console.log('Failed');
                console.log(error);
                res.send(error);
            });
            } else {
            console.log('Failed: file does not exist at:' + this.DB_PATH);
            res.send('Database could not connect - Please contact admin');
            }
        }
        catch (error) {
            console.log('error:'.error);
            res.send(error);
        } finally {
            console.log('Complete');
        }
    }
}

Please advise, thanks, am I doing this wrong?

Error thrown on module require statement

When loading the module with:

var ADODB = require('node-adodb');

The following error occurs:

path.js:360
        throw new TypeError('Arguments to path.join must be strings');
              ^
TypeError: Arguments to path.join must be strings
    at exports.join (path.js:360:15)
    at Array.filter (native)
    at Object.exports.join (path.js:358:36)
    at Object.<anonymous> (/Users/user1/Desktop/Development/dashboard/node_modules/node-adodb/lib/process.js:12:30)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)

Process finished with exit code 8

Error in Dates, new version 3.0.3

In the new version is not fixed the error of Dates, just read the empty fields of the same as 'null', those containing a date do not appear.

"message": "对象关闭时,不允许操作。"

下面是我的出错信息:
Exec: query
Params: {
"connection": "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DSCDdata.mdb;",
"sql": "select sensorno as id,data1 as datavalue,unit1 as unit,right(date,10)+
' '+left(time,10) as times from data where date >=#2016-06-00# and time > cdate(
'17:59:55') and sensortype = 'JMZX-212AT'"
}
Error: {
"valid": false,
"message": "对象关闭时,不允许操作。"
}

似乎是ADODB.open()未能正确打开,如何知道ADODB.open() 已经正确执行,多谢

Query not returning dates from table.

I have an Access table with a column that holds dates in the Date/Time datatype. When querying that table using node-adodb, I cannot select by date, nor will a SELECT * return any values from a column that is a Date/Time type.

Execute only one query at time

I have a Node.js application that add records to an Access 97 database (that I cannot change). Sometimes I get multiple identical records, but I'm trying to avoid this:

`
var DB = require('node-adodb'), dbConnection = DB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + settings.database.path + settings.database.db);

// Add only if there isn't an identical record
query = 'INSERT INTO ' + table + '(' + fields + ') ';
query += ' SELECT TOP 1 ' + values;
query += ' FROM ' + table;
query += ' WHERE NOT EXISTS ( SELECT 1 FROM ' + table + ' WHERE ';

array.forEach(function(element)
{
query += "([" + element.name + "]=" + element.value + ") AND ";
});
query = query.substr(0, query.length - 4);
query += ' );';

dbConnection
.execute(query)
.on('done', function (data) {
return callback({id: id, success: true});
})
.on('fail', function (data) {
console.log(data);
return callback({id: id, success: false});
});
`

I'm afraid if the client makes several requests in a while, each one won't find the record, and all will be add.

How should I avoid this?

Metadata: No information about the fields within a recordset

I don't think it's possible to get information about the fields within a recordset. e.g. Type and DefinedSize. In regular ADO I would be examining the Recordset's Fields collection, but I can see that approach isn't available with node-adodb.

I'm not saying I want to be able to write code that's completely data-driven, but it's nice for a program to be able to look that the fields so this information doesn't have to be duplicated and hard-coded, and so it can be tolerant of small changes to the database. The problem is particularly acute if a recordset is empty, because then you don't even get a list of fields.

The other thing I've tried to solve this problem myself is accessing the MSysObjects table. I think this is a bad approach, and the problem I encountered is nothing to do with node-adodb, but for the sake of completeness: Let's edit your example query.js file, just to change the table name and put in some error handling:

'use strict';

// External lib
var ADODB = require('../');

// Variable declaration
var connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=node-adodb.mdb;');

process.env.DEBUG = 'ADODB';

connection
  .query('SELECT * FROM MSysObjects')
  .on('done', function(data) {
    console.log('result:', JSON.stringify(data, null, 2));
  })
  .on('fail', function(msg) {
    console.log(msg);
  });

node-adodb

"Syntax error in FROM clause." using LIMIT in query

Thank you for putting this out there - this is a much needed help to my current project!

Everything is working fine for normal SELECT queries, but sadly, when I add a LIMIT to my query to node-adodb, i receive an error every time:
"Syntax error in FROM clause."

Here is my code:

//orders.js file

'use strict';
module.exports = (req, res, next) => {
    return DB_QUERY("SELECT * FROM Orders LIMIT 10", req, res, next);
};

//index.js file
const adodb = require('node-adodb');
const restify = require('restify');
require('restify').plugins;

server.use(restify.plugins.queryParser({ mapParams: true }));
server.use(restify.plugins.bodyParser({ mapParams: true }));
server.use(restify.plugins.acceptParser(server.acceptable));

var DB_PATH = 'C:\\data\\data.mdb';
var ADODB = adodb.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + DB_PATH);

var DB_QUERY = function(dbQuery, req, res, next, pics){
    var isWin = /^win/.test(process.platform);
    if(!isWin){
      res.send('This should be run on a Windows Machine only to connect to Access DB File at: ' + DB_PATH);
    } else {
        try {
            if (fs.existsSync(DB_PATH)) {
            ADODB.query(dbQuery, true)
            .on('done', function(data) {
                console.log(dbQuery.cyan);
                // console.log('data',data);
                res.send(data);
            })
            .on('fail', function(error) {
                console.log('Failed');
                console.log(error);
                res.send(error);
            });
            } else {
            console.log('Failed: file does not exist at:' + this.DB_PATH);
            res.send('Database could not connect - Please contact admin');
            }
        }
        catch (error) {
            console.log('error:'.error);
            res.send(error);
        } finally {
            console.log('Complete');
        }
    }
}

Is this a known issues, that I should look into fixing myself, or am i missing something?

Please advise, thanks!

English Readme.md

Hi there!

I've successfully used this module to communicate with a Microsoft Access db 👍. Would it be possible to include an English version of your readme?

Error: Cannot find module 'debug'

Running on Windows 10 x64.

What is the correct process to test this library using the examples
provided?

peter@Merry-Christmas MINGW64 /c/ae/ae-node-adodb/examples (aedev)
$ node --version
v8.6.0

peter@Merry-Christmas MINGW64 /c/ae/ae-node-adodb/examples (aedev)
$ npm --version
5.3.0

peter@Merry-Christmas MINGW64 /c/ae/ae-node-adodb/examples (aedev)
$
peter@Merry-Christmas MINGW64 /c/ae/ae-node-adodb (aedev)
$ cd examples

peter@Merry-Christmas MINGW64 /c/ae/ae-node-adodb/examples (aedev)
$ node execute.js
module.js:529
    throw err;
    ^

Error: Cannot find module 'debug'
    at Function.Module._resolveFilename (module.js:527:15)
    at Function.Module._load (module.js:476:23)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\ae\ae-node-adodb\lib\utils.js:4:13)
    at Module._compile (module.js:624:30)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)

Unable to run queries after archived with asar

My app pulls data from an .mdb file quite fine using this plugin.
The .mdb file is located on a windows 8 x64 machine on C:\storage folder.
After archiving my app for distribution/installation usin asar my app is no longer able to run queries. It simply fails to read the file an run any queries.
Any solution/workaround on this? please? :)

node-adodb on Debian

Hello,

This package works really fine on my Windows 7, but I got an error on my Debian server when I try to do:
var ADODB = require('node-adodb');

This is the error:

module.js:340 throw err; ^ Error: Cannot find module 'node-adodb' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.<anonymous> (/var/www/pegase/dbManager.js:12:13) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:364:17)

Anyone can help ?

SELECT not working

Hello, I found an issue when developing with adodb. I have created an access database (.accdb) and connected it using adodb. It seems that I can CREATE, INSERT and anything that basically writes to the databse, but I cannot seem to read anything. (SELECT doesn't work). This is my code:

var express = require('express')
var app = express()
var fs = require('fs')
var adodb = require('node-adodb')
adodb.debug = true

var connection = adodb.open('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=' + __dirname + '/WorkDB.accdb;Persist Security Info=False;')

app.get('/', async (request, response) => {
  var query = connection.execute("SELECT * FROM Employees")
  var data = await query;
  console.log("Data:", data)
  response.send(JSON.stringify(data))
})

app.listen(8080, err => {
  if(err) console.error(err)
  else console.log("Server listening on port 8080")
})

But every test gives [] as result.

Details:

  • node-adodb v4.0.9
  • Windows 7 x84
  • ms Access 10 (ACE.OLEDB.12.0)

Binary data retrieval from mdb file?

Thank you for an excellent plugin, I have it currently powering my node/express api and it is very efficient for my SELECT queries, which is as far as I have gotten with it.

My problem: I have .jpg image data binary encoded in a relational .mdb database - I would like to use nodeADODB to retrieve the binary data using a select query (or similar), so I can use node to then import the binary data and display it at an image endpoint in my api or write it to a local image file

It is beyond my knowledge how to do this with your plugin's ADO connection, but would be a huge help if you can please provide me with a place to start.

EG:
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-binary-data

Output formatting example in README

In the examples given in the README part of the console output is:

'Result:'.green.bold

How is this supposed to work? green seems to be undefined.

connection
  .execute('INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Newton", "Male", 25)')
  .on('done', function (data){
    console.log('Result:'.green.bold, JSON.stringify(data, null, '  ').bold);
  })
  .on('fail', function (data){
    // TODO 逻辑处理
  });

Using scalar parameter does not return a value

When using the posted node-adodb example database and code I'm failing to retrieve a @@Identity response when the query executes:
connection .execute( 'INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Newton", "Male", 25)', 'SELECT @@Identity AS id' ) .on('done', function(data) { console.log('result:', JSON.stringify(data, null, ' ')); }) .on('fail', function(error) { // TODO 逻辑处理 });
All that is returned in the data object is:
result: { "valid": true, "message": "Execute SQL: INSER INTO Users(UserName,UserSex,UserAge) VALUES(\"Newtonz", \"Male\", 25) success!"}
There is no attribute relating to the @@Identity sql statement. (I wanted to use this to return the autoNumber id value when data is inserted).

Syntax error in INSERT INTO statement

Get a 'Syntax error in INSERT INTO statement' on attempt to insert data into Access database table with an auto increment ID column and specifying which columns to insert.

The insert is successful if no columns are specified and all columns are given a value.

This is Access 2007 compatible file running on Windows 7.

throw new TypeError('Path must be a string. Received ' + inspect(path));

Have just installed node-adodb and am getting this error at the require statement

path.js:7
throw new TypeError('Path must be a string. Received ' + inspect(path));
^

TypeError: Path must be a string. Received undefined
at assertPath (path.js:7:11)
at Object.join (path.js:1211:7)
at Object. (/home/ubuntu/workspace/ILTProjectsV1/node_modules/node-adodb/lib/proxy.js:15:20)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)

Process exited with code: 1

Access 97

Please, can you tell me if it is possible to connect with Acces97 (16bits).
Thank you.

It works perfectly on runtime node but not in PKG

Hi and thanks for your great Job !

i just use the adodb provider : Microsoft.ACE.OLEDB.12.0 with the schema function of the ado connection.

it's ok when i use it with node.

Our project needs to use PKG to deliver an executable file.
And every thing is ok, no error, but nothing happens with the schema function : no error, no result

Have you and idea ? Thanks.

David

my code :

var adodb = require('node-adodb');
const connection = adodb.open('Provider=' + provider + ';Data Source=' + file + ';User ID=admin;Persist Security Info=False;');

var adSchemaTables = 20 // TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE
var adSchemaConstraintColumnUsage = 6
var schema

try {
schema = await connection.schema(adSchemaTables); // HERE NOTHING WITH PKG OK WITH NODE
} catch(err) {
logger.error(err)
}

Fields schema

// https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/datatypeenum
var DataTypeEnum = {
  0x2000: 'AdArray',
  20: 'adBigInt',
  128: 'adBinary',
  11: 'adBoolean',
  8: 'adBSTR',
  136: 'adChapter',
  129: 'adChar',
  6: 'adCurrency',
  7: 'adDate',
  133: 'adDBDate',
  134: 'adDBTime',
  135: 'adDBTimeStamp',
  14: 'adDecimal',
  5: 'adDouble',
  0: 'adEmpty',
  10: 'adError',
  64: 'adFileTime',
  72: 'adGUID',
  9: 'adIDispatch',
  3: 'adInteger',
  13: 'adIUnknown',
  205: 'adLongVarBinary',
  201: 'adLongVarChar',
  203: 'adLongVarWChar',
  131: 'adNumeric',
  138: 'adPropVariant',
  4: 'adSingle',
  2: 'adSmallInt',
  16: 'adTinyInt',
  21: 'adUnsignedBigInt',
  19: 'adUnsignedInt',
  18: 'adUnsignedSmallInt',
  17: 'adUnsignedTinyInt',
  132: 'adUserDefined',
  204: 'adVarBinary',
  200: 'adVarChar',
  12: 'adVariant',
  139: 'adVarNumeric',
  202: 'adVarWChar',
  130: 'adWChar'
};

// https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/fieldattributeenum
var FieldAttributeEnum = {
  0x1000: 'adFldCacheDeferred',
  0x10: 'adFldFixed',
  0x2000: 'adFldIsChapter',
  0x40000: 'adFldIsCollection',
  0x8000: 'adFldKeyColumn',
  0x20000: 'adFldIsDefaultStream',
  0x20: 'adFldIsNullable',
  0x10000: 'adFldIsRowURL',
  0x80: 'adFldLong',
  0x40: 'adFldMayBeNull',
  0x2: 'adFldMayDefer',
  0x4000: 'adFldNegativeScale',
  0x100: 'adFldRowID',
  0x200: 'adFldRowVersion',
  0x8: 'adFldUnknownUpdatable',
  0xFFFFFFFF: 'adFldUnspecified',
  0x4: 'adFldUpdatable'
};

function resolveType(type) {
  return DataTypeEnum[type];
}

function resolveAttr(attr) {
  var flags = {};

  if (typeof attr !== 'number') {
    return flags;
  }

  var value;

  for (var key in FieldAttributeEnum) {
    value = FieldAttributeEnum[key];

    if (key & attr) {
      flags[value] = true;
      attr -= key;
    }
  }

  return flags;
}

module.exports = {
  resolveType: resolveType,
  resolveAttr: resolveAttr
};

Not include to node-adodb, user custom.

Returning small amount of data from a large db

I'm returning 208 rows back from a table that has over 2000 rows. Is there something that I'm missing? I want to be able to return the entire table.

Config file

var config = {
    port: 4444,
    mdb: "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=PATH TO .MDB FILE;"
};

module.exports = config;

Query

var queries = {
    dashboard: "SELECT * FROM [EXAMPLE_TABLE];"
};

module.exports = queries;

The call

var ADODB       = require('node-adodb'),
    config      = require('../config/_config'),
    q           = require('../queries/cplLinkRgaWarranty'),
    connection  = ADODB.open(config.mdb),
    data        = [];

ADODB.debug = true;

connection
    .query(q.dashboard)
    .on('done', function(obj) {
        console.log(obj.records.length);
        for(var i=0; i<obj.records.length; i++) {
            data.push(obj.records[i]);
        };
    })
    .on('fail', function(err) {
        console.log("Error: " + err);
    })

var service = {
    data: data
};

module.exports = service;

Return Identity after INSERT INTO request

Hello,

I have a problem with an INSERT INTO request. I must get the @@IDENTITY after add data into my table. But unfortunately, I don't know how to perform this with node-adodb.

In ASP.NET, I just made a SELECT @@IDENTITYbefore closing the connection.

Thank you to enlighten me.

EDIT: I have made some changes in your library. I will fork your project and push my changes.

Error on query of .accdb file: database in state that prevents opening

When trying to execute a query on an Access 2013, I get the following error:
The database has been placed in a state by user 'Admin' on machine 'xxxxx' that prevents it from being opened or locked.

Here is my code:

const ADODB = require('node-adodb')
const connection = ADODB.open(
  'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\XXXX\\Documents\\database.accdb;Persist Security Info=False;'
)
connection.query('SELECT * FROM Table1').then(console.log).catch(console.error)

*.mdb files work fine though.

Date fields not being returned in query result

I've noticed an issue with date fields not being returned in the result of a query.

Sample code:

var ADODB = require('node-adodb');
ADODB.debug = true;

var connection = ADODB.open('Data Source=SOTAMAS90;');
var query = `SELECT SalesOrderNo, OrderDate, OrderStatus
  FROM SO_SalesOrderHeader
  WHERE OrderType <> 'Q'
  LIMIT 4`;

connection
  .query(query)
  .on('done', function (data) {
    console.log(data.records);
  })
  .on('fail', function (err) {
    console.log(err);
  });

result:

[ { SalesOrderNo: '0149064', OrderStatus: 'O' },
  { SalesOrderNo: '0153153', OrderStatus: 'O' },
  { SalesOrderNo: '0154751', OrderStatus: 'O' },
  { SalesOrderNo: '0154754', OrderStatus: 'O' } ]

My solution, while not optimal, was to add the following to adodb.js in the switch statement of function str()

function str(key, holder) {
  ...
  switch (typeof value) {
    ...
    case 'date':
        return isFinite(value) ? value + 0 : null;
   ...
  }
 ...
}

New result:

[ { SalesOrderNo: '0149064', OrderDate: 1411538400000, OrderStatus: 'O' },
  { SalesOrderNo: '0153153', OrderDate: 1422342000000, OrderStatus: 'O' },
  { SalesOrderNo: '0154751', OrderDate: 1425880800000, OrderStatus: 'O' },
  { SalesOrderNo: '0154754', OrderDate: 1425880800000, OrderStatus: 'O' } ]

Is it possible to run node-adodb inside of a Docker container

I am going to be running a the process that is utilizing node-adodb to connect to an Access database on a Windows Server box. I am considering using Docker to containerize the Node process. Docker containers run inside of a Linux VM.

Is it possible to use this package inside of a Linux VM or is it dependent on drivers that are provided by the Windows operating system?

当数据库数据有特殊字符的时候数据返回会失败

例如一个 lang 表,有语言 العربية, 在原数据返回逻辑下会出现错误。

现将数据返回逻辑修改如下:
返回数据统一编码成 Base64 编码,这样即避免了特殊字符造成的无法预计的错误,又能跳过编码转换这一环节。所以新版本去除 encoding 设置

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.