cancel
Showing results for 
Search instead for 
Did you mean: 

XSJS - db table select statement with input parameter

0 Kudos
1,135

Hi All,

I'm very new to XSJS and I'm trying to learn it.. I went through the Reference guide but found it difficult to find the syntax of a select statement on the db table with input parameter and how to call this XSJS in the web browser. I'm using the below code and saved/activated it as customer.XSJS

try {
	$.response.contentType = "text/html";
	var output = "Hello, " + $.session.getUsername() + " <br><br>";
	var conn = $.db.getConnection();
var id = $.request.parameters.get("id");
var query = "SELECT  MTART FROM <SCHEMA>.MARA WHERE MATNR like ?";
var pstmt = conn.prepareStatement( query );
pstmt.setString(1, "'%"+id+"%'");
var rs = pstmt.executeQuery(); 
if (!rs.next()) {
	$.response.setBody( "Failed to retrieve data" );
	$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
	}
else {
	output = output + "This is the Material Number is" + rs.getString(1);
	}
rs.close();
pstmt.close();
conn.close();
$.response.setBody(output);
}
catch (e){
	$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
	$.response.setBody(e.message);
	}

and when i execute the link ( http://<SERVER-NAME>/<PACKAGE-NAME>/customer.xsjs?id=<VALUE>; ) i just get "Hello, <USERNAME>. I don't get the results for the "ELSE" part of my If statement even though there is an entry in the db.

When i modify my XSJS with no input parameter and run it, i get the output. Just the XSJS with input parameter is not giving me the results.


Accepted Solutions (1)

Accepted Solutions (1)

pfefferf
Active Contributor
0 Kudos

Hi,

when you set the parameter for the prepared statement you do not have to use single quotes to enclose the id value including the "%" signs.

You have to do it without single quotes:

pstmt.setString(1, "%" + id + "%")

Regards,
Florian

PS: In general you should think about to use the new $.hdb DB interface instead of the legacy interface $.db.

0 Kudos

Thanks Florian. Its working now.

Answers (0)