Oracle and Nodejs - can't bind parameters in SQL statement - sql

Hi I have the following statement that I execute using node-oracle
await connection.execute(`SELECT * FROM TABLE WHERE NAME LIKE '%And%'`)
But now I want to bind a parameter instead of using a hard coded value
const queryText = 'And';
await connection.execute(`SELECT * FROM TABLE WHERE NAME LIKE '%:queryText%'`, {queryText});
it throws Error: ORA-01036: illegal variable name/number
What is the correct way of binding a parameter here, since the documentation doesn't cover this situation?

Try with the following:
const queryText = 'And';
await connection.execute(
"SELECT * FROM TABLE WHERE NAME LIKE :queryText",
{
queryText: { dir: oracledb.BIND_IN, val: '%'+ queryText +'%', type: oracledb.STRING }
});

Use string concatenation:
SELECT * FROM TABLE WHERE NAME LIKE '%' || :queryText || '%'

Here is a working example.
let queryText = "John"
let sql = "SELECT * FROM TABLE WHERE NAME LIKE :queryText"
let binds = {queryTarget: {dir: oracledb.BIND_IN, val: queryText, type: oracledb.STRING}}
let result = await connection.execute(sql, binds, options)
Do not add '%' like the other people suggested.

Related

How to 'replace' table name in raw SQL query?

I have the following SQL query, which works:
await sequelize.query(
"DELETE FROM `table_name` WHERE (?) IN (?)",
{
replacements: ["project_id", projectIds],
type: QueryTypes.DELETE,
}
);
But I also want to use a replacement for table_name like this:
await sequelize.query(
"DELETE FROM (?) WHERE (?) IN (?)",
{
replacements: ["table_name", "project_id", projectIds],
type: QueryTypes.DELETE,
}
);
But this doesn't work and generates an error about SQL syntax. How can I make this work?
You are mixing data value binding and quoting identifiers.
There is ancient issue in the repo: https://github.com/sequelize/sequelize/issues/4494, which sounds like the problem above.
I believe you can create a workaround that respects different sql dialects like this:
const queryInterface = sequelize.getQueryInterface();
const tableName = queryInterface.quoteIdentifier("projects");
const columnName = queryInterface.quoteIdentifier("project_id");
await sequelize.query(`DELETE FROM ${tableName} WHERE ${columnName} IN (?)`, {
replacements: [project_ids],
type: QueryTypes.DELETE,
});
Assuming you are using sequelize 6.x.

Issue in Sqlite while using Node js. Like operator and parameters

So I am trying to select rows based on user input, as shown below:
db.all(
'SELECT * FROM houses WHERE location LIKE "%$input%"',
{
$input: name,
},
(error, rows) => {
res.send(rows);
}
);
However, the database responds with an undefined value. What can I do?
You are not using query parameters properly. Consider:
db.all(
"SELECT * FROM houses WHERE location LIKE '%' || ? || '%",
[name],
(error,rows) => { ... }
);
It might be slightly more efficient to concatenate the variable in the js code:
db.all(
"SELECT * FROM houses WHERE location LIKE ?",
['%' + name + '%'],
(error,rows) => { ... }
);

Node-postgres: named parameters query (nodejs)

I used to name my parameters in my SQL query when preparing it for practical reasons like in php with PDO.
So can I use named parameters with node-postgres module?
For now, I saw many examples and docs on internet showing queries like so:
client.query("SELECT * FROM foo WHERE id = $1 AND color = $2", [22, 'blue']);
But is this also correct?
client.query("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'});
or this
client.query("SELECT * FROM foo WHERE id = ? AND color = ?", [22, 'blue']);
I'm asking this because of the numbered parameter $n that doesn't help me in the case of queries built dynamically.
There is a library for what you are trying to do. Here's how:
var sql = require('yesql').pg
client.query(sql("SELECT * FROM foo WHERE id = :id AND color = :color")({id: 22, color: 'blue'}));
QueryConvert to the rescue. It will take a parameterized sql string and an object and converts it to pg conforming query config.
type QueryReducerArray = [string, any[], number];
export function queryConvert(parameterizedSql: string, params: Dict<any>) {
const [text, values] = Object.entries(params).reduce(
([sql, array, index], [key, value]) => [sql.replace(`:${key}`, `$${index}`), [...array, value], index + 1] as QueryReducerArray,
[parameterizedSql, [], 1] as QueryReducerArray
);
return { text, values };
}
Usage would be as follows:
client.query(queryConvert("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'}));
Not exactly what the OP is asking for. But you could also use:
import SQL from 'sql-template-strings';
client.query(SQL`SELECT * FROM unicorn WHERE color = ${colorName}`)
It uses tag functions in combination with template literals to embed the values
I have been working with nodejs and postgres. I usually execute queries like this:
client.query("DELETE FROM vehiculo WHERE vehiculo_id= $1", [id], function (err, result){ //Delete a record in de db
if(err){
client.end();//Close de data base conection
//Error code here
}
else{
client.end();
//Some code here
}
});

nhibernate CreateCriteria wildcard Like when

In SQL I can write
SELECT blah FROM Clients
Where #p1 Like '%'+lastname+'%'
How do I represent this with CreateCriteria in Nhibernate?
I've tried s.CreateCriteria<Client>.Add(Restrictions.Where<Client>(c => "something".Contains(c.LastName))
but get an error
System.Exception: Unrecognised method call: System.String:Boolean Contains(System.String)\r\n at NHibernate.Impl.ExpressionProcessor.ProcessCustomMethodCall(MethodCallExpression methodCallExpression)
I've also tried
s.CreateCriteria<Client>.Add(Restrictions.Where<Client>(c => "something".IndexOf(c.LastName) != -1))
but get
"variable 'c' of type 'TrinityFinance.Data.Entities.Client' referenced from scope '', but it is not defined"
Note the order is important here.
#p1 Like '%'+lastname+'%'
is not the same as
lastname Like '%'+#p1+'%'
s.CreateCriteria<Client>().Add(
Restrictions.InsensitiveLike( "LastName", "something", MatchMode.Anywhere))
Thanks to a friend I've solved my issue.
var searchCriteria = GetSession().CreateCriteria<Client>();
searchCriteria.Add(Expression.Sql(string.Format("'{0}' like '%' + {1} + '%'", p.ClientInputText,p.DbField)));
var results = searchCriteria.List<Client>();
For Case-Insensitive %Like% Search
Criteria criteria = session.createCriteria(Any.class);
criteria.add(Restrictions.ilike(propertyName, value, MatchMode.ANYWHERE);
criteria.list();

how to use like query in drupal

How to write SQL LIKE Query in drupal ,
SELECT title FROM { node } WHERE type='%s'
i want to add the LIKE CONDITION IN THAT
SELECT title FROM { node } WHERE type='%s' AND LIKE '%S%'
i think i writtern wrong like query formnat, can rewrite and tell me,
Just use % to escape.
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');
while ($row = db_fetch_object($result)) {
// do stuff with the data
}
Node type does not need escaping.
And here is an example with how to use LIKE in a dynamic query (Drupal 7 Only):
$query = db_select('node', 'n')
->fields('n', array('title'))
->condition('type', 'my_type')
->condition('title', '%' . db_like(search_string) . '%', 'LIKE');
$result = $query->execute()->fetchCol();
db_like() is used to escapes characters that work as wildcard characters in a LIKE pattern.
drupal_query replace %% to % and %s to value string
so your code will be
$sql = "SELECT title FROM node WHERE type='%%%s' AND title LIKE '%%%S%%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
OK, so you want the LIKE operator to refer to the title column. Use this query:
$sql = "SELECT title FROM node WHERE type='%s' AND title LIKE '%S%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
This is because the LIKE operator requires a column name to be specified. Otherwise, your database doesn't have any idea what value you want to perform the comparison on. See here.