I am having trouble moving this line from MySQL
SELECT * FROM table WHERE columnName LIKE '?%'
to my method in node.js
getName(request, respond){
var columnName = request.params.columnName;
var sql = "SELECT * FROM table WHERE columnName LIKE '?%'";
db.query(sql, columnName, function(error, result){
if(error){
throw error;
}
else{
respond.json(result);
}
});
}
What is the correct syntax for the LIKE '?%'
Thank you so much!
This question is probably answered in various places in Stack Overflow already, but after searching briefly, I couldn't find one with the particular combination of mysql and node.js, so here goes:
You're on the right track using query parameters, but the following won't work, because parameter placeholders can't be inside an SQL string literal. Otherwise, how would you ever use an actual "?" character in an SQL string?
var sql = "SELECT * FROM table WHERE columnName LIKE '?%'";
You can use parameter placeholders only outside the string delimiters, even if the parameter is for a string or date value.
Your options are to concatentate the parameter with a literal '%' in an SQL expression like the answer from #tcadidot0:
var sql = "SELECT * FROM table WHERE columnName LIKE CONCAT(?, '%')";
Or alternatively, concatenate the wildcard to your input string in Node.js code, and treat the concatenated value as a single string:
var columnNamePattern = request.params.columnName + "%";
var sql = "SELECT * FROM table WHERE columnName LIKE ?";
db.query(sql, columnNamePattern, function(error, result){
Please avoid concatenating Node.js variables into your SQL query. That creates an SQL injection vulnerability.
NOT SAFE:
var sql = "SELECT * FROM table WHERE columnName LIKE '" + columnName + "%'";
It's also more difficult to write code in the unsafe way. It's harder to spot mismatched quotes, it takes longer to write the code, it's hard to debug.
You can change the LIKE '?%' to LIKE CONCAT(?,'%');
getName(request, respond){
var columnName = request.params.columnName;
var sql = "SELECT * FROM table WHERE columnName LIKE CONCAT(?,'%')";
db.query(sql, columnName, function(error, result){
if(error){
throw error;
}
else{
respond.json(result);
}
});
}
Related
I wonder if is there equivalent of try catch blocks from javascript in pure sql in Snowflake.
I want to have a procedure which will check all views and does something with them, but some of the views are invalid and these I want to skip.
The javascript version looks like this:
create or replace procedure test_views_js()
returns varchar
language javascript
as
$$
var sql = "select table_name from INFORMATION_SCHEMA.views where table_schema='TEST'";
var stmt = snowflake.createStatement ({sqlText:sql});
var result_set = stmt.execute();
var cnt = 0;
while (result_set.next()){
try{
var sql_text = "select count(*) from "+result_set.getColumnValue(1);
var stmt2 = snowflake.createStatement ({sqlText:sql_text});
var r = stmt2.execute();
r.next();
cnt+=r.getColumnValue(1);
}catch (err){
continue
}
}
return cnt;
$$
Can I achieve the same result with sql?
UPDATE
I am getting syntax error when I try to put exception in the loop. When it's in different place syntax is valid, but 'break is outside of loop' . Maybe there is some obvious typo that i cannot see?
create or replace procedure test_views()
returns integer not null
language sql
as
declare
sel varchar;
row_cnt integer default 0;
res resultset default
(select table_name
from INFORMATION_SCHEMA.views
where table_schema='TEST') ;
c1 cursor for res;
begin
for row_variable in c1 do
row_cnt:= (select count(*) from view_test);
exception when statement_error then continue;
end for;
return row_cnt;
end;
It is possible to use exception inside loop. Instead of:
for row_variable in c1 do
row_cnt:= (select count(*) from view_test);
exception when statement_error then continue;
end for;
All the code should be wrapped with its own BEGIN EXCEPTION END block.
create or replace procedure test_views()
returns integer not null
language sql
as
declare
sel varchar;
row_cnt integer default 0;
res resultset default
(select table_name
from INFORMATION_SCHEMA.views
where table_schema='TEST') ;
c1 cursor for res;
begin
for row_variable in c1 do
begin
row_cnt:= (select count(*) from view_test);
exception when other then continue;
end;
end for;
return row_cnt;
end;
Yes - there RAISE/EXCEPTION constructs documented here: https://docs.snowflake.com/en/developer-guide/snowflake-scripting/exceptions.html
I'm trying to insert values using mysql in nodejs. I had written the following code and installed MySQL support via npm,But canot to INSERT INTO the table due to this problem.
My code;
var mysql = require('mysql');
var values=randomValueHex(8);
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`)
VALUES ( values ,'3')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
My Error on terminal:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''3')'
How can i solve this problem?
Why are you using back quote for the column names? We do not need that in column names. You can simply create your dynamic sql query by using + operator on the column values like this:
var sql = "INSERT INTO activationkeys (activationKey, productId) VALUES ( " + values + " ,'3')";
Instead of
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`)
VALUES ( values ,'3')";
Please try this
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`)
VALUES ( " + values + " ,'3')";
provided values is a string
values currently means nothing the way you're using it in the SQL query.
What is values? Is it an integer, or a string?
Nevertheless, you need to concatenate the values variable within the string.
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`) VALUES (" + values + ",'3')";
And one more correction values variable have to give like this '" + values + "' . This is the most correct way of define as a variables. Otherwise you give like this " + values + " , you may be have an error accure like this Error: ER_BAD_FIELD_ERROR: Unknown column 'xxxxxx' in 'field list'. And my code is
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`) VALUES ( '" + values + "' , 3 )";
This is simple way to write SQL query in you JavaScript code.
Try It Once
const QUERY = INSERT INTO users (firstName, lastName) VALUES ( "${firstName}", "${lastName}")
Note: Please wrap your complete query into the back ticks.
I want to pass a table as parameter on an ajax callback procedure in Oracle APEX 5, because I need to make an SQL query on that table.
The SQL process is stored as shared component inside the Apex 5 application. Screenshot
My procedure is like this
(procedure name: THIS_PROCESS)
declare
v_tablename varchar(128);--max table_name lenght
v_ID number;
v_somevar
BEGIN
SELECT Columname,
INTO v_somevar
FROM v_tablename
WHERE ID = v_ID;
--Do stuff
END;
This code (FROM v_tablename) gives me a compilation error:
ORA-00942: table or view does not exist ORA-06550: line 9, column 5:
PL/SQL: SQL Statement ignored
I'm a total newbie. I had been reading that I should call that procedure with this javascript:
apex.server.process ( "THIS_PROCESS", {
x01: "TABLENAME",
x02: "Row_ID",
pageItems: "#P1_Item,#P2_Item"
},{
success: function( pData )
// do something here
}
} );
I do not understand why I should pass x01 and x02 instead of v_tablename and v_ID
Do x01 and x02 automatically are assigned to v_tablename and v_ID?
Here's an example page process THIS_PROCESS of type "Ajax Callback". Note that you need Dynamic SQL to select from a table name that isn't hardcoded.
declare
v_table varchar2(128) := apex_application.g_x01;
v_id number := apex_application.g_x02;
v_somevar varchar2(100);
v_sql varchar2(4000);
begin
-- validate v_table parameter to avoid sql injection. will throw exception if it fails
select table_name into v_table from all_tables where table_name = v_table;
v_sql := 'SELECT Columname
FROM ' || v_table || '
WHERE ID = :A1';
execute immediate v_sql into v_somevar using v_id;
-- do something with v_somevar
end;
Do be careful with this sort of thing - this design will allow a malicious user to write their own javascript function which can pass any table name that it likes to your procedure.
You need to use dynamic sql:
declare
v_tablename varchar(128);--max table_name lenght
v_sql varchar2(1000);
v_ID number;
v_somevar varchar2(100);
BEGIN
v_sql := 'SELECT Columname FROM ' || v_tablename || ' where ID = :1';
EXECUTE IMMEDIATE v_sql INTO v_somevar USING v_ID;
--Do stuff
END;
/
In my Cordova app, I need to query a SQLite database and select rows where the value of the column EventName contains a substring. I want to be able to use ? to hold values to avoid SQL injection. I tried this query:
SELECT * FROM EventName WHERE 1 = 1 AND lower(EventName) LIKE lower('%?%');
This is my JavaScript code that I use to query the database:
function searchEvent(onSearch, eventName) {
// First create the query string
var params = [];
var query = "SELECT * FROM Event WHERE 1 = 1";
if (eventName != null && eventName != "") {
query += " AND lower(EventName) LIKE lower('%?%')";
params.push(eventName);
}
query += ";";
console.log(query); // Log the query
console.log(params); // Log the parameters
// Then execute query statement
db.transaction(function(tx) {
tx.executeSql(query, params, function(tx, rs) {
onSearch(rs);
});
}, function(err) {
console.log(err); // This statement was executed
});
}
This is the logged query:
SELECT * FROM Event WHERE 1 = 1 AND lower(EventName) LIKE
lower('%?%');
This is the logged paramaters:
[ 'myInput' ]
This is the error the was returned:
{
code: 5,
messsage: 'number of \'?\'s in statement string does not match argument count'
}
As you can see there is 1 ? placeholder and 1 input parameter so the numbers DO match. I think it is because the ? is between the single quotes ('') so it is thought to be a part of the searched string. How do I fix this?
EDIT:
The JavaScript statement "SELECT * FROM Event WHERE 1 = 1" + " AND lower(EventName) LIKE lower('%" + eventName + "%')" is ok, but I wanna use a method that can protect me against SQL injection
In order to prevent the eventName from SQL injection, check it with regEx validation to include only alphanumneric and whitelist specific special characters /^[ A-Za-z0-9_#./#&+-]*$/. Also try this regEx /^[a-zA-Z0-9!##\$%\^\&*)(+=._-]+$/g. I do not believe that ? would work with SQL SELECT statement, so you need to pass +eventname+
Hope it helps.
I am trying to get a random geometry from a PostGIS enabled PostgreSQL database using nodejs, but when I attempt to even do the first query, to get the 'max' automatically-generated, sequential ID in the dataset, it throws the above error. I recognise that the error is because it's expecting a string rather than a numeric value, but as the 'gid' field is numeric, i'm not sure how to solve this.
Any help explaining the issue/fixing it so I can get my random object from the database would be extremely helpful. Thanks in advance.
var db = new pg.Client(conString);
db.connect();
function getRandObj(){
var max = db.query( " SELECT MAX(`gid`) FROM `buildings` ");
//var min = db.query( " SELECT MIN(`gid`) FROM `buildings` ");
//var random = mt_rand( min , max );
//var result = db.query( " ST_AsGeoJSON(geom) FROM `buildings` WHERE `gid` >= random LIMIT 0,1 ");
//return result
}
I haven't messed with node.js too much, but, I have experimented a little. Looking at your code here:
var max = db.query( " SELECT MAX(`gid`) FROM `buildings` ");
I see a couple of potential issues. First, the backquotes. I think they are a mistake. Change that query to read:
var max = db.query( " SELECT MAX(gid) FROM buildings ");
Or, if you really want to see quotes in there, you should be using "name" quotes, like:
var max = db.query( ' SELECT MAX("gid") FROM "buildings" ');
The second thing is the return value. I don't think you get direct returns like that. Have you tried something like this:
var max = -1;
q = db.query(' SELECT MAX("gid") FROM "buildings" as mx ');
q.on('row', function (row) {
console.log(row);
max = row.mx;
};
console.log("max is %d", max);
-g