Reputation: 1751
I'm new to xsjs, i know to retrieve data from db(HANA db) we need to use prepare statements. I tried using it but any how my .xsjs file is returning me empty JSON. can some one help me? Sharing my code. Below is user table
id | user_name | password | marks
1 | Prasanna | test@123 | 10
2 | sasne | test@123 | 20
3 | Ankush | test@123 | 0
4 | Shubham | test@123 | 30
5 | Anupama | test@123 | 15
Now i want to write get request for accessing data according to id
requested.
My XSJS code is as follows
if ($.request.method === $.net.http.GET) {
var conn = $.db.getConnection();
var id = $.request.parameters.get('id');
var statement = 'SELECT * FROM "USER_TABLE" WHERE ID = ?';
$.response.contentType = "application/json";
try {
var pstmt = conn.prepareStatement(statement);
pstmt.setString(1, id);
var result = pstmt.executeQuery();
$.response.setBody(JSON.stringify(result));
$.response.status = $.net.http.OK;
} catch (ex) {
$.response.setBody(ex.toString());
} finally {
if (conn) {
conn.close();
}
}
}
Help will be appriciated
Upvotes: 0
Views: 1142
Reputation: 2645
This should work, just checked it:
if ($.request.method === $.net.http.GET) {
const id = $.request.parameters.get('id');
$.response.contentType = "application/json";
const conn = $.hdb.getConnection();
try {
const resultSet = conn.executeQuery('select * from "user_table" where "id" = ?', id);
$.response.setBody(JSON.stringify(resultSet));
$.response.status = $.net.http.OK;
} catch (ex) {
$.response.setBody(ex.toString());
} finally {
if (conn) {
conn.close();
}
}
}
I think that your problem was that id was not in double quotes ("), this is quite important.
As you can see with hdb connection it becomes easier and hopefully even faster to handle the sql queries, so use this one instead of db - link to hdb documentation.
Moreover, use debugger to investigate the issue (I have heard that there are some issues debugging xsjs files in Eclipse, but I do it without problems in Intellij IDEA). And yes, I would guess that your id
is unique thus you could/should get only one row and then stringify
only resultSet[0]
.
Upvotes: 0