Concatenating a SQL string query in a JSP file - java

I have a html page that allows users to enter specific search terms to query the database I've created. The problem I'm having is that when I pass the string to execute as a sql query, it is not wrapping the query in single quotes which is needed to search for a string match in a sql database. Here is the code I have currently:
//Create a statement for the sql queries
java.sql.Statement stmt = conn.createStatement();
//Get results from queries entered
String result_event_name = request.getParameter("event_name");
//Create query string
String sqlQuery_event = "SELECT event_name FROM event where event_name = " + "\'" + result_event_name + "\'";
//execute query
java.sql.ResultSet rs_event = stmt.executeQuery(sqlQuery_event);`
This is the error I get:
SQLException: ERROR: syntax error at end of input Position: 49
I tried using prepare statement -- returns same error
I tried the query without escaping -- returns same error
I tried with no single quotes -- returns same error

The single quote ' only needs escaping once LIKE '%\'%'
But to query backslash \ you need to double escape to LIKE '%\\\\%'
If you wanted to query backslash+singlequote \' then LIKE '%\\\\\'%'
(with 5 backslashes)
Explanation Source excerpt:
Because MySQL uses C escape syntax in strings (for example, “\n” to
represent a newline character), you must double any “\” that you use
in LIKE strings. For example, to search for “\n”, specify it as “\n”.
To search for “\”, specify it as “\”; this is because the backslashes
are stripped once by the parser and again when the pattern match is
made, leaving a single backslash to be matched against.
Credit goes to xchiltonx
Resource Link:
mysql - How to handle query search with special characters /(forward slash) and \(backslash)

Related

Single Quote issue with Oracle 12 C JDBC [duplicate]

I'm having issues dealing with the single quote while using it in a prepared statement in JAVA via Oracle JDBC.
Let's say we have a table Restaurant with a column restaurant_name with 1 value : Jack's Deli
I want to use a simple prepared statement query like this:
String result = "Jack\'\'s Deli"
String sqlStatement = "select * from Restaurant where restauraunt_name like ? escape '\\' ";
PreparedStatement pStmt = conn.prepareStatement(sqlStatement);
pstmt.setString(1, result);
The result shows 0 returned values, however when I directly search the query in the database (ORACLE) it works fine and retrieves the result. (Oracle uses two single quotes as an escape for the first)
I am thinking that the value is not being passed properly to the database. Or there is some other formatting issue.
The point of prepared statements is that you don't need any escaping.
.setString(1, "Jack's Deli") will get it done.

How to replace a string with another string and the replaced string will have arguments of first string in it using RegExp

I have a string
String SQL = "SELECT POSITION('Bengal' IN STRING) from delivery";
I want to replace the POSITION() function from the SQL string with this String INSTR(STRING,'Bengal'). And in the POSITION function of SQL String 'Bengal' and STRING is not a fixed values it will change as per user requirement but POSITION,the open braces "(",IN and closing braces ")" is static.
The final out put has to be look like this using Regular Expression.
String SQL ="SELECT INSTR(STRING,'Bengal') from delivery";
So in the string if it repeats two times then it has to replace two time with corresponding arguments into the same string SQL.
Any help will be appreciated.
In Java, use this Regex:
SQL = SQL.replaceAll("POSITION\\((.*?) IN ([A-Z]+)\\)", "INSTR($2, $1)");
Note, however, that it will work only for simple cases of the input String, if the first parameter is some expression and second is something more complex, it may not work. It will even work for multiple POSITION expressions in the query, such as this:
String SQL = "SELECT POSITION('Bengal''s something IN d' IN STRING), POSITION('text' IN STRINGX) from delivery";
SQL = SQL.replaceAll("POSITION\\((.*?) IN ([A-Z]+)\\)", "INSTR($2, $1)");
// SQL now contains: "String SQL = "SELECT INSTR(STRING, 'Bengal''s something IN d'), INSTR(STRINGX, 'text') from delivery";"
If you want to completely correctly replace the function call, use proper sqlparser. In the past I used JSQLParser. It can handle even subselects as POSITION parameters with nested POSITION calls.

select column name from H2 with columns that have spaces

I am attempting to query from a tab delimited file with H2 and java. When I select * there are no problems, however, one of the columns has a space in the column name. When I try to query on just that column I get an exception:
Caused by: org.h2.jdbc.JdbcSQLException: Column "EXAMPLE" not found; SQL statement:
It appears as though it is not grabbing both words in the column name (Example ColumnName), but only grabbing the first.
This is what I have:
System.out.println( simpleJdbcTemplate.queryForList( "SELECT Example ColumnName FROM CSVREAD('" + fileName
+ "', null,'UTF-8', chr(9)) where send = 1;", new Object[] {} ) );
I'm guessing there is a special syntax to do this, but I can't seem to find it. I've tried enclosing the column name in: square brackets, single quotes, double quotes, tick marks all to no avail.
Is there a way to query H2 using columns that have spaces in the name?
According to the documentation, double quotes should do the trick.
Remember to escape them correctly in Java, i.e. to just store your column name in a String, use
String exampleColumnName = "\"Example ColumnName\"";
Also, note it is case sensitive, from the documentation:
Quoted names are case sensitive
You can also use brackets [] if you set "MODE=MSSQLServer" in your connection properties. Example:
SELECT * FROM [My Table]
The connection string would look something like this:
jdbc:h2:~/test;MODE=MSSQLServer

I have stuck with the simplest SQL query in java

I can't find the correct syntax of the following query in java,please help me.
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"' ";
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"'";
I think that the mistake is how to end the query...
Since I got the error Check the manual that corresponds to your MySQL server version for the right syntax to use near ''Customer'' at line 1
when I choose Customer table
You want to use backticks instead of single quotes around your object names.
String st = "SELECT COUNT(`"+id+"`) FROM `"+selected_table+"` ";
Table names should be surrounded by tick marks (`), not single quotes (')
String st = "SELECT COUNT('"+id+"') FROM `"+selected_table+"`";
^ use tick marks ^
What are the values of id and selected_table? What is the actual query string that is sent to the database?
Also, it's rarely a good idea to manually build a query like this using string concatenation. This makes it very easy for a bug to result in a gaping security hole, and it's a lot more difficult (and risky) to try to secure this approach than it is to just do it right.
Looks from your query that you are enclosing your id and selected_table in single quotes... For example, SELECT COUNT('ID') FROM 'CUSTOMER' which is wrong. should be in backtics `` or nothing...

Hibernate criteria.list bad results with quotes and accents

I'm using hibernate 3.6 and i'm having problems using criteria.list. I need search words with quotes or accents like "d'eau" or "d´eau". My code is something like this:
Criteria criteria;
criteria.add(Restrictions.ilike("nameParam", "d''eau", MatchMode.ANYWHERE));
I put two single quotes because i'm working with a sql server database. There are 2 single quotes because single quote escapes with another single quote.
The statement has 0 results, but if I execute the sql statement printed in the log in the sql server client, I get 120 results aprox.
Testing with HQL and the same sql statement. I get this:
String hqlQuery = "select distinct(t) from Table t where b.idCon in (select t2.idCon from Table t2 where lower(t2.outTerTb) like '%d''eau%')";
List qwer = getEntityManager().createQuery(hqlQuery).getResultList();
System.out.println("qwer.size() -> " + qwer.size());
String hqlQuery2 = "select distinct(t) from Table t where b.idCon in (select t2.idCon from Table t2 where lower(t2.outTerTb) like :param)";
List qwer2 = getEntityManager().createQuery(hqlQuery2).setParameter("param", "%d''eau%").getResultList();
System.out.println("qwer2.size() -> " + qwer2.size());
This code print:
qwer.size() -> 120
qwer2.size() -> 0
And I don't understand why this happens.
Sorry if my english is bad
You don't need to escape single quotes in your parameters. That's the whole point of using parameters (in Hibernate and, behind the scenes, in the JDBC prepared statements): the JDBC driver escapes everything that needs to be escaped for you.
You take what comes from the UI layer as is and stuff it into parameters, everything isproperly escaped by the driver, and you don't risk any SQL injection attack.

Categories