IBM Worklight - Error while using variable in a SQL Adapter query - sql

I am using SQL adapter in worklight where I need to have a variable that I need to use it in the query.
I read here and followed the same. But it`s showing the below error.
Pasted the complete error message on using a variable in the SQL adapter.
[ERROR ] FWLSE0099E: An error occurred while invoking procedure [project Sample]Device/SqlStatementFWLSE0100E: parameters: [project Sample]{
"arr": [
{
"parameters": [
null
],
"preparedStatement": "UPDATE devices SET DeviceQuantity=$[count] WHERE DeviceNames = 'DellTestLap';"
}
]
}
Parameter index out of range (1 > number of parameters, which is 0)..
Performed query:
UPDATE devices SET DeviceQuantity=$[count] WHERE DeviceNames = 'DellTestLap';
FWLSE0101E: Caused by: [project Sample]java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
com.worklight.common.log.filters.ErrorFilter
Project.js
function UpdateDeviceDetails(){
var count = 2;
var invocationData2 = {
adapter : 'Device', // adapter name
procedure : 'UpdateDeviceDetails', // procedure name
parameters : [count]
};
WL.Client.invokeProcedure(invocationData2,{
onSuccess : QuerySuccess,
onFailure : QueryFailure
});
}
Adapter.js
var DeviceDetails = WL.Server.createSQLStatement("UPDATE devices SET DeviceQuantity=$[count] WHERE DeviceNames = 'DellTestLap';");
function UpdateDeviceDetails(count) {
return WL.Server.invokeSQLStatement({
preparedStatement :DeviceDetails,
parameters : [count]
});
}

I've never used the $[variable_name] syntax with SQL adapters. I've always used "?"
"UPDATE devices SET DeviceQuantity=? WHERE DeviceNames =
'DellTestLap';"
However, assuming that this syntax does work, how is your code referencing the name "count"? The variable "count" is resolved as the number 2. The SQL statement won't be able to know to reference the name count just by the variable name. It would make more sense if the variable passed to parameters was more like this:
return WL.Server.invokeSQLStatement({
preparedStatement :DeviceDetails,
parameters : [{ count: 2 }]
});
That being said, I've never used this syntax before, I just use the "?" syntax.

You can also use the syntax of ?
var DeviceDetails = WL.Server.createSQLStatement("UPDATE devices SET DeviceQuantity=? WHERE DeviceNames ='DellTestLap';");
this will work surely try it !!!!!!!!!!!!!

Related

How to correct bad sql grammar when passing data?

This is my JDBC file with a the following sql query:
private static final String UPDATE_QUESTION = "UPDATE Quiz SET type=?, questionIndex=?, choiceNum=?, question=?, choiceA=?, choiceB=?, choiceC=?, choiceD=?, correct=?, hint=? WHERE type=? AND questionIndex=?";
When I try and pass some data into the query above in JSON format:
{
"id": 84,
"type":"epidemics",
"questionIndex": 1,
"choiceNum":2,
"question":"updated question3",
"choiceA": "no3",
"choiceB":"yes2",
"choiceC":"no3",
"choiceD":"yes4",
"correct":"no3",
"hint":"second answer"
}
I am getting the following error message:
"timestamp": "2022-11-26T11:52:16.431+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE Quiz SET type=?, questionIndex=?, choiceNum=?, question=?, choiceA=?, choiceB=?, choiceC=?, choiceD=?, correct=?, hint=? WHERE (type=?) AND (questionIndex=?)]; nested exception is java.sql.SQLException: No value specified for parameter 12
Any ideas where I'm going wrong in the query?
Note that you need to pass a value for each ? placeholder, even if the same column appears more than once in the prepared statement. So, you need to bind the value for questionIndex twice. Your Java code should look something like:
String UPDATE_QUESTION = "UPDATE Quiz SET type=?, questionIndex=?, choiceNum=?, question=?, choiceA=?, choiceB=?, choiceC=?, choiceD=?, correct=?, hint=? WHERE type=? AND questionIndex=?";
PreparedStatement ps = conn.prepareStatement(UPDATE_QUESTION);
ps.setString(1, type);
ps.setInt(2, questionIndex); // first setter for questionIndex
ps.setInt(3, choiceNum);
ps.setString(4, question);
ps.setString(5, choiceA);
ps.setString(6, choiceB);
ps.setString(7, choiceC);
ps.setString(8, choiceD);
ps.setString(9, correct);
ps.setString(10, hint);
ps.setString(11, type);
ps.setInt(12, questionIndex); // second setter for questionIndex
int row = ps.executeUpdate();
// rows affected
System.out.println(row);

Do strings need to be escaped inside parametrized queries?

I'm discovering Express by creating a simple CRUD without ORM.
Issue is, I'm not able to find any record through the Model.findBy() function
model User {
static async findBy(payload) {
try {
let attr = Object.keys(payload)[0]
let value = Object.values(payload)[0]
let user = await pool.query(
`SELECT * from users WHERE $1::text = $2::text LIMIT 1;`,
[attr, value]
);
return user.rows; // empty :-(
} catch (err) {
throw err
}
}
}
User.findBy({ email: 'foo#bar.baz' }).then(console.log);
User.findBy({ name: 'Foo' }).then(console.log);
I've no issue using psql if I surround $2::text by single quote ' like:
SELECT * FROM users WHERE email = 'foo#bar.baz' LIMIT 1;
Though that's not possible inside parametrized queries. I've tried stuff like '($2::text)' (and escaped variations), but that looks far from what the documentation recommends.
I must be missing something. Is the emptiness of user.rows related to the way I fetch attr & value ? Or maybe, is some kind of escape required when passing string parameters ?
"Answer":
As stated in the comment section, issue isn't related to string escape, but to dynamic column names.
Column names are not identifiers, and therefore cannot be dynamically set using a query parameter.
See: https://stackoverflow.com/a/50813577/11509906

Error when trying to call SAP HANA stored procedure from service side

I am trying to call a SAP HANA hdbprocedure from my service side using below code.
var con = ConLib.getHDBConnection();
var uploadStmt = con.loadProcedure("_SYS_BIC" , "procname");
var result = uploadStmt("samplefield1", "samplefield2", {"DATA":[{"id1":"id_1001","id2":"id_2001","year_col":"2018"}, {"id1":"id_1002","id2":"id_2002","year_col":"2019"}]})
The procedure takes below paramaters as input.
PROCEDURE procname (
IN field1 VARCHAR(100),
IN field2 VARCHAR(100)
IN in_table_data "schema_name"."hdbdd_file_name.table_type"
){}
The in_table_data is defined as below in hdbdd_file_name.hdbdd file.
Type table_type {
id1 : String(100);
id2 : String(100);
year_col : String(4);}
I am getting below error when I call the procedure from my service side.
" Error occured in processRequest method $.hdb.Connection.executeProcedure: Parameter at position 3 is not of type that can be processed "
Could you please suggest what needs to be changed either at the DB side or service side to fix this issue.
Thank you in advance.
I'm under the impression that the definition of the array in your calling statement is incorrect:
var result = uploadStmt("samplefield1", "samplefield2", {"DATA":[{"id1":"id_1001","id2":"id_2001","year_col":"2018"}, {"id1":"id_1002","id2":"id_2002","year_col":"2019"}]})
instead, try it like so:
var result = uploadStmt("samplefield1"
, "samplefield2"
, [{id1: 'id_1001', id2: 'id_2001', year_col: '2018'}
, {id1: 'id_1002', id2: 'id_2002', year_col: '2019'}]
)

Run SQL Query in Phonegap

Hello everyone i am trying to run a query as follows, but i always get "SQL ERROR: undefined"
What am i doing wrong.
db = window.openDatabase("Database", "1.0", "SQLDB", 200000);
RunQuery ("DROP TABLE IF EXISTS ARTIGOS");
function RunQuery(QueryExecute) {
db.transaction(function(transaction){
transaction.executeSql(QueryExecute,successCB,errorCB);
})
}
function errorCB(err) {
alert("SQL Error: "+err.message);
}
function successCB() {
alert("SQL OK");
}
One possibility is that the transaction.executeSql method takes a parameters array as its second argument. So to use the callbacks like you have, you may have to pass in an empty array for the parameters. e.g.:
transaction.executeSql(QueryExecute, [], successCB, errorCB);
Referenced from the Cordova docs here:
https://cordova.apache.org/docs/en/latest/cordova/storage/storage.html

How to update database using adapters in mobilefirst 7.1

I am able to successfully create adapter for creation and insertion in sql but updation i have doubt below is my code where i want to update a certain field values based on wrkname and i am getting in or out error.
var updateStatement = WL.Server.createSQLStatement("UPDATE office1 SET wrkid=?, wrkname=?, empref=? WHERE wrkname=?");
function updateoffice(wrkid,wrkname,empref,wrkname) {
return WL.Server.invokeSQLStatement({
preparedStatement : updateStatement,
parameters : [wrkid,wrkname,empref,wrkname]
});
}
Aren't you missing the fourth parameter, wrkname (which you're using twice...)?
For example, this worked well for me:
var update = WL.Server.createSQLStatement("UPDATE users SET stdid=? WHERE userId=?");
function updatevaluesprocedure(stdId,userId) {
return WL.Server.invokeSQLStatement({
preparedStatement : update,
parameters : [stdId,userId]
});
}
Two parameters are expected, two parameters were received.
In your case four parameters are expected...