使用 Node.js 连接 Amazon Redshift 数据库并将数据提取到 Array 中

使用 JDBC 连接 amazon redshift 的最佳方法,根据版本使用适当的驱动程序 http://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html

第 1 步:npm 安装 jdbc

第 2 步:

var JDBC = require('jdbc');
var jinst = require('jdbc/lib/jinst');
// isJvmCreated will be true after the first java call.  When this happens, the
// options and classpath cannot be adjusted.
if (!jinst.isJvmCreated()) {
  // Add all java options required by your project here.  You get one chance to
  // setup the options before the first java call.
  jinst.addOption("-Xrs");
  // Add all jar files required by your project here.  You get one chance to
  // setup the classpath before the first java call.
  jinst.setupClasspath(['./drivers/hsqldb.jar',
                        './drivers/derby.jar',
                        './drivers/derbyclient.jar',
                        './drivers/derbytools.jar',
                        './lib/drivers/RedshiftJDBC41-1.1.10.1010.jar'
                        ]);
}

var config = {
  url: 'jdbc:redshift://test-redshift.czac2vcs84ci.us-east-.redshift.amazonaws.com:5439/testredshift?user=redshift&password=W9P3GC42GJYFpGxBitxPszAc8iZFW',
  drivername: 'com.amazon.redshift.jdbc41.Driver',
  user : 'username',
  password: 'password',
  minpoolsize: 10,
  maxpoolsize: 100
};
var hsqldbInit = false;
GLOBAL.hsqldb = new JDBC(config);`

步骤 3:npm install async(使用异步模块查询代码)(可选)

步骤 4:手动创建一个数据库名称 test 和 table sample_data在这里找到 amazon redshift database 命令

第五步:

var asyncjs = require('async');
hsqldb.reserve(function(err, connObj) {
    if (connObj) {
        console.log("Connection: " + connObj.uuid);
        var conn = connObj.conn;
        asyncjs.series([
            function(callback) {
                conn.createStatement(function(err, statement) {
                    if (err) {
                        callback(err);
                    } else {
                        statement.setFetchSize(100, function(err) {
                            if (err) {
                                callback(err);
                            } else {
                              statement.executeQuery("SELECT * FROM test.sample_data", function(err, resultset) {
                                resultset.toObjArray(function(err,sresults){
                                  console.log(sresults);
                                });   
                              });   
                           }
                        })
                      }
                    })
                 }
              ]) 
         }
      })