简体   繁体   中英

connect to Redshift from lambda and fetch some record using python

is any one able successfully connect to Redshift from lambda.

I want to fetch some records from Redshift table and feed to my bot (aws lex)

Please suggest - this code is working outside lambda how to make it work inside lambda.

import psycopg2

con=psycopg2.connect(dbname= 'qa', host='name',
port= '5439', user= 'dwuser', password= '1234567')

cur = con.cursor()

cur.execute("SELECT * FROM pk.fact  limit 4;")

for result in cur:
    print (result)
cur.close()
con.close()

Here is the node lambda that works to connecting to Redshift and pulling data from it.

exports.handler = function(event, context, callback) {
    var response = {
        status: "SUCCESS",
        errors: [],
        response: {},
        verbose: {}
    };

    var client = new pg.Client(connectionString);
    client.connect(function(err) {
        if (err) {
            callback('Could not connect to RedShift ' + JSON.stringify(err));
        } else {
            client.query(sql.Sql, function(err, result) {
                client.end();
                if (err) {
                    callback('Error Cleaning up Redshift' + err);
                } else {
                    callback(null, ' Good ' + JSON.stringify(result));
                }
            });
        }
    });
};

Hope it helps.

You need to fetch the records first.

results = cur.fetchall()
for result in results:
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM