Run SQL Query in Phonegap - sql

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

Related

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

Calling multi-parameterized Azure SQL stored procedure from Nodejs

I am looking forward to know how can I run an Azure SQL stored procedure with multiple input parameters from Nodejs.
For example, if I have a stored procedure FIND_USERS(activity_status, color, gender) which runs a query
select * from users where isActive = activity_status and bay_color = color and userGender = gender;
I should be able to call this stored procedure from nodejs with the input parameters. The thing to understand here is that I want have a SQL transaction service that can take any CALL PROCEDURE type command along with the set of input parameters and call the procedure using those input parameters irrespective of the number of input parameters.
What I know is that for MySQL, there is a mysql library which lets me run procedures with multiple parameters. I have encapsulated it in MySQLConnector.js service as
var mysql = require('mysql');
exports.query = function(sql, values, next) {
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection({
host:host,
user:user,
password:password,
database:database
});
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
console.log(err == 'Error: ER_CON_COUNT_ERROR: Too many connections')
if(err == 'Error: ER_CON_COUNT_ERROR: Too many connections'){
connection.end();
}
}
});
connection.query(sql, values, function(err) {
connection.end();
if (err) {
throw err;
}
next.apply(this, arguments);
});
}
With this, I can call a stored procedure from nodejs with a function like
MySQLConnector.query('CALL FIND_USERS (?, ?, ?)', [1, 'blue', 'female'], function(err, userData) {
//do something with userData
});
How is it possible to do this for Azure MS SQL?
You can use tedious driver to connect to SQL Server. It supports both input+output parameter for statements and SPs, you can find the example in http://tediousjs.github.io/tedious/parameters.html
Feels free to raise an issue in GitHub if you need more assistance.
Make use of Edje.js and you should create a function and send the parameters when you call the function.
getHorarioFarmacia({pSede:'Sucursal Parrita'}, function (error, result){....
}
For more details, read the comments made by Luis Diego Pizarro here.

Test contents of return array in PHPSpec

Say I have this method of a RuleFactory:
public function makeFromArray($rules)
{
$array = [];
foreach ($rules as $rule) {
$array[] = new Rule($rule[0], $rule[1]);
}
return $array;
}
I want to test that the return array contains Rule elements. Here is my test:
function it_should_create_multiple_rules_at_once()
{
$rules = [
['required', 'Please provide your first name'],
['alpha', 'Please provide a valid first name']
];
$this->makeFromArray($rules)->shouldHaveCount(2);
$this->makeFromArray($rules)[0]->shouldBeInstanceOf('Rule');
$this->makeFromArray($rules)[1]->shouldBeInstanceOf('Rule');
}
But this does not work, it throws an error in PHPSpec.
The strange thing is that I can do this just fine on other methods that return arrays, but for some reason I cannot do that here.
The error I get is this:
! it should create multiple rules at once
method [array:2] not found
How do I test the contents of this return array, WITHOUT creating my own inline matcher?
Your method accepts a single rule, not all of them. The spec should be:
$this->makeFromArray($rules)->shouldHaveCount(2);
$this->makeFromArray($rules[0])[0]->shouldBeAnInstanceOf('Rule');
$this->makeFromArray($rules[1])[1]->shouldBeAnInstanceOf('Rule');
Or, to avoid multiple calls:
$rules = $this->makeFromArray($rules);
$rules->shouldHaveCount(2);
$rules[0]->shouldBeAnInstanceOf('Rule');
$rules[1]->shouldBeAnInstanceOf('Rule');
Still, the most readable version would be the one leveraging a custom matcher:
$rules->shouldHaveCount(2);
$rules->shouldContainOnlyInstancesOf('Rule');

NHibernate Criteria Filtering

I use this code to filter database records
if (!string.IsNullOrEmpty(_searchCriteria.MessageType))
{
var messageType = (AutotransferMessageType)Enum.Parse(typeof(AutotransferMessageType), _searchCriteria.MessageType, true);
if (Enum.IsDefined(typeof(AutotransferMessageType), messageType))
{
criteriaQuery.CreateAlias("AutotransferInputRecord", "AutotransferInputRecord")
.Add(
Restrictions.Eq(
"AutotransferInputRecord." + AutotransferLogSearchCriteria.MessageTypePropertyName,
messageType));
}
else
{
criteriaQuery.Add(Restrictions.IsNull("AutotransferInputRecord"));
}
}
AutotransferMessageType is enumerable type
public enum AutotransferMessageType
{
[DisplayName("MT202")]
[DatabaseName("MT202")]
MT202,
[DisplayName("MT210")]
[DatabaseName("MT210")]
MT210,
//...
}
My filter outputs the results when I enter MT202, for example. (It's the right behavior).
When I input just number, for example, 202, I get no results (It's the right behavior too).
But when I try to input some line, "mt", for example, I get error
Unexpected application error has been occured:
'Requested value 'mt' was not found.'
How to make the filter do not show any results when I input a line?
Your error is coming from the line that parses the enum. Use Enum.TryParse instead:
AutotransferMessageType msgEnum;
var enumPrasedOk = Enum.TryParse(_searchCriteria.MessageType, true, out msgEnum);
if(enumPrasedOk){
//Do something
}else{
//Handle case where enum was not found for some reason (if need be)
}
Also please note that you can not look up the enum this way using it's description (in your case they are the same so it is ok).

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

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 !!!!!!!!!!!!!