使用 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);
});
});
}
})
}
})
}
])
}
})