SqlAlchemy Programming Error when using raw SQL Like operator [duplicate] - sql

This question already has an answer here:
CS50: LIKE operator, variable substitution with % expansion
(1 answer)
Closed 2 years ago.
I am trying to run a SQL query in my Flask application to search a database. However, I get an error when I run the query:
db.execute("SELECT * FROM books WHERE author LIKE '%:author%' ", {"author":query})
The resulting error is this (passed 'Tom' in my input):
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "Tom"
LINE 1: SELECT * FROM books WHERE author LIKE '%'Tom'%'
^
[SQL: SELECT * FROM books WHERE author LIKE '%%%(author)s%%' ]
[parameters: {'author': 'Tom'}]
(Background on this error at: http://sqlalche.me/e/f405)
I've tested the query with a hard coded value and it works fine. I would like to know what is causing the error and how to fix it.

You need string concatenation. Many SQL databases support concat() (and other have an equivalent function or operator, such as standard operator ||):
db.execute("SELECT * FROM books WHERE author LIKE CONCAT('%', :author, '%')", {"author":query})
Another option is to concatenate '%'s around your parameter in your application first, and then pass it to the query.

Related

select globalmap using tDBinput with Talend give the error: Invalid character constant

I have to remove the accents from the person's name, but I cannot apply the function in Talend while it works in SQL oracle.
this query works in my tDBInput component :
"SELECT '"+((String)globalMap.get("copyOfSORTIE.NOM"))+"' as nom_nom_compl,
'"+((String)globalMap.get("copyOfSORTIE.ENTETE"))+"' entete
FROM DUAL"
However, when I want to add the convert function, it doesn't work
this query does not work :
"SELECT '"+((String)globalMap.get(CONVERT("copyOfSORTIE.NOM",'US7ASCII')))+"' as nom_nom_compl,
'"+((String)globalMap.get("copyOfSORTIE.ENTETE"))+"' entete
FROM DUAL"
In my talend :
I am getting this error
What is the syntax for it to work?
Thank you!
Two things there :
I don't know the CONVERT method, but I can see that you are applying it to the key of your globalMap variable , and not the value (as if you wanted to convert "myKey" and not "myValue" which is attached to the key). Are you sure this is what you want to achieve ? if not, the syntax should be something similar to "SELECT CONVERT('"+((String)globalMap.get("copyOfSORTIE.NOM"))+"','US7ASCII') "
A useful java method implemented in talend is TalendString.removeAccents("") that you can apply directly on your talend variable, thus not using a SQL method.

Escaping ? (question mark) in hibernate/gorm sql restriction

I'm attempting to query against a materialized path stored with postgres ltree type from a Grails application. Unfortunately, my query uses the "?" operator which is being captured by GORM as a parameter
sqlRestriction("materialized_path ? (SELECT ARRAY(SELECT CAST(CAST(subpath(?,0,generate_series) AS text) ||'.*{1}' AS lquery) FROM generate_series(1,nlevel(CAST(? AS lquery)))))"
,[vertex.materializedPath,vertex.materializedPath])
Where that first question mark should be escaped and the error being thrown is
org.postgresql.util.PSQLException: No value specified for parameter 4.
at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:246)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:272)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:430)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:356)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:168)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:116)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
Found it myself with a little experimentation. It just takes a double-question mark. So,
"materialized_path ? (SELECT ARRAY(...
becomes
"materialized_path ?? (SELECT ARRAY(

SQL wildcards via Ruby

I am trying to use a wildcard or regular expression to give some leeway with user input in retrieving information from a database in a simple library catalog program, written in Ruby.
The code in question (which currently works if there is an exact match):
puts "Enter the title of the book"
title = gets.chomp
book = $db.execute("SELECT * FROM books WHERE title LIKE ?", title).first
puts %Q{Title:#{book['title']}
Author:#{book['auth_first']} #{book['auth_last']}
Country:#{book['country']}}
I am using SQLite 3. In the SQLite terminal I can enter:
SELECT * FROM books WHERE title LIKE 'Moby%'
or
SELECT * FROM books WHERE title LIKE "Moby%"
and get (assuming there's a proper entry):
Title: Moby-Dick
Author: Herman Melville
Country: USA
I can't figure out any corresponding way of doing this in my Ruby program.
Is it not possible to use the SQL % wildcard character in this context? If so, do I need to use a Ruby regular expression here? What is a good way of handling this?
(Even putting the ? in single quotes ('?') will cause it to no longer work in the program.)
Any help is greatly appreciated.
(Note: I am essentially just trying to modify the sample code from chapter 9 of Beginning Ruby (Peter Cooper).)
The pattern you give to SQL's LIKE is just a string with optional pattern characters. That means that you can build the pattern in Ruby:
$db.execute("SELECT * FROM books WHERE title LIKE ?", "%#{title}%")
or do the string work in SQL:
$db.execute("SELECT * FROM books WHERE title LIKE '%' || ? || '%'", title)
Note that the case sensitivity of LIKE is database dependent but SQLite's is case insensitive so you don't have to worry about that until you try to switch database. Different databases have different ways of dealing with this, some have a case insensitive LIKE, some have a separate ILIKE case insensitive version of LIKE, and some make you normalize the case yourself.

Use of LIKE clause in sql prepared statement, spring, SimpleJDBCTemplate

I have the following sql prepared statement:
SELECT * FROM video WHERE video_name LIKE ?
Im using spring and jdbc.
i have a method, where term is a searchterm, sjt is a SimpleJdbcTemplate, VideoMapper is a RowMapper and searchForTermQuery is the string from above
...
return sjt.query(searchForTermQuery, new VideoMapper(), term);
My table has 2 videos that match the term.
However when I run the query none is found. I get an empty List.
I tried playing with % around the question mark, but it only gave badGrammarExceptions.
You need to put the % around the value itself, not around the placeholder (the question mark).
So:
return sjt.query(searchForTermQuery, new VideoMapper(), "%" + term + "%");

SQL Syntax Error near ADD [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I've been staring at this thing for a while now and I can't seem to figure out what the syntax error is. I've been in this situation before and last time it was something so unbelievably simple I felt stupid afterwards. But here's to another attempt:
//update database
$q = "
UPDATE
users
SET
id='$edit_id',
name='$edit_name',
bdm='$edit_bdm',
add='$edit_add',
pc='$edit_pc',
location='$edit_outletL',
style='$edit_outletS',
coName='$edit_coName',
coNum='$edit_coTel',
coEmail='$edit_coEmail',
password='$edit_pass'
WHERE
id='$query_title'
";
$edit_query = mysql_query($q) or die("Database Query Error: ". mysql_error());
Database Query 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 'add='Llancadle, Nr Barry', pc='CF62 3AQ', location='rural', style='food', coName' at line 1
You neeed to backquote add since it is a keyword:
`add` = ...
I think add is a reserved word in MySQL.
your problem is that "add" is a MySQL reserved word. See: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html. If you have a column named "add", escape it like this:
//update database
$edit_query = mysql_query("UPDATE users SET id='$edit_id', name='$edit_name', bdm='$edit_bdm', `add`='$edit_add', pc='$edit_pc', location='$edit_outletL', style='$edit_outletS', coName='$edit_coName', coNum='$edit_coTel', coEmail='$edit_coEmail', password='$edit_pass' WHERE id='$query_title'") or die("Database Query Error: ". mysql_error());
as bobby noted in a comment, add is a mysql reserved word
`add`='$edit_add'
will tell mysql you are talking about a column