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.
Related
I'm trying to execute following SQL query where it tries to find results that matches the column2 values ending with abc
PreparedStatement stmt = conn.prepareStatement("SELECT column1 FROM dbo.table1 WHERE column2 LIKE ?");
stmt.setString(1, "%" +"abc");
But it returns nothing even though there is a matching value. This only happens with SQL Server. Same query with informix database returns correct results. Anyone has an idea about what causing this to behave differently?
Is this due to an issue in how PreparedStatement creates the SQL query for SQL Server?
Edit
I found out this happens when the data in the column which i perform the like contain space. eg: when the column contains "some word" and if i perform the search by stmt.setString(1, "%" + "word"); it won't return a matching result but if i perform the same on for "someword" it would return the matching result
SQL Server accepts wild characters in the LIKE clause within the single quotation marks, like this ''.
A sample SQL query:
SELECT NAME FROM VERSIONS WHERE NAME LIKE 'Upd%'
The query above will yield you results on SQL Server. Applying the same logic to your Java code will retrieve results from your PreparedStatement as well.
PreparedStatement stmt = conn.prepareStatement("SELECT NAME FROM VERSIONS WHERE NAME LIKE ?");
stmt.setString(1, "Upd%");
I've tested this code on SQL Server 2012 and it works for me. You need to ensure that there are no trailing spaces in the search literal that you pass on to your JDBC code.
Though as a side note, you need to understand that a wildcard % used in the beginning, enforces a full table scan on the table which can deteriorate your query performance. A good article for your future reference.
Hope this helps!
i have same problem,i have done with the CONCATE function for this.
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
ps.setString(1, notes);
ResultSet rs = ps.executeQuery();
I have a search query which must search a column in a table using contains search. There is ctxsys.context type index on the column. While fetching data on the table using prepared statement, the search query is not able to process special characters like -,/,_ etc.
Here is my code -
String query = "select * from parties where contains (party_name ,'%' || ? || '%')>0";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, searchName);
The code works fine for text which doesn't have special characters.
When I run the below query in sqlDeveloper it runs fine .
select * from parties where contains(party_name,'c/o')>0;
Please suggest what changes should I make in the prepared statement to make it work for special characters too.
Please refer to this question on how to use contains in prepared statement.
PreparedStatement with CONTAINS query
You have to use escape in your queries if the above didint work
like
SELECT * FROM BIRDS WHERE SPECIES='Williamson's Sapsucker
statement.executeQuery("SELECT * FROM BIRDS WHERE SPECIES='Williamson/'s Sapsucker' {escape '/'}");
reference from http://www.jguru.com/faq/view.jsp?EID=8881
I'm facing an issue with insertion to SQL database from java code.
I'm using INSERT sql query using the java code to enter the data from XML file to SQL database.
You may suppose column named "Description".
Imagine there is a record in XML which contains apostrophe ('). The program crashes due to the error caused by the apostrophe which is included in the data.
I know that manually we can add another apostrophe and make it work, but imagine data of 10.000 records, how can we handle this issue?
Don't do this (string concatenation):
String sql = "insert into MyTable (description) values ('" + value + "')";
Statement st = connection.createStatement();
st.executeUpdate(sql);
Do do this (prepared statement):
PreparedStatement ps = connection.prepareStatement(
"insert into MyTable (description) values (?)"
);
ps.setString(1, value);
pt.executeUpdate();
The value will get correctly escaped for you. Not only does this protect against mishaps like the one you mentioned, it also helps defend you from SQL injection attacks.
Humorous illustration:
Source
You have two options, you should use PreparedStatement and bind your parameter(s). Or, if you really, really, want - you could use StringEscapeUtils.escapeSql(str).
I am using a JDBC connection to fetch data from an Access database.
The database design is not my control. In the database there are columns that have "?" included in their names, for example: Open?, Paid?, and lots more.
When I try to fetch data with a PreparedStatement it gives me an error. The query is:
SELECT Open? FROM tblJobList WHERE WeekEnding=?
I also tried to use brackets like [Open?], but the result is the same.
The error I receive is "Too few parameters ..." as I am pushing only one parameter into the PreparedStatement.
I can not use normal statement because of WeekEnding=? as this value is a Timestamp and I could not manage to work it with Statement. Only prepared statement works here.
Can anyone tell me how to use these kind of column names in a PreparedStatement?
use the " character
"SELECT \"Open?\" FROM tblJobList WHERE WeekEnding=?"
tested this against oracle and appears to work with mssqlserver
How to select a column in SQL Server with a special character in the column name?
Just to update this for current technologies:
While the JDBC-ODBC Bridge and Access ODBC were unable to handle a PreparedStatement with a column name containing a question mark, the UCanAccess JDBC driver handles it just fine, as can be confirmed with the following code:
String connectionUrl = "jdbc:ucanaccess://C:/Users/Public/UCanAccessTest.accdb";
Connection conn = DriverManager.getConnection(connectionUrl);
String sql = "SELECT ID, [Open?] FROM tblJobList WHERE WeekEnding=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("2016-01-01"));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.printf("%d: %s%n", rs.getInt("ID"), rs.getBoolean("Open?"));
}
conn.close();
For more information on UCanAccess, see
Manipulating an Access database from Java without ODBC
I am not sure but you can try // to escape the special meaning of ? and to use it as a normal character. Like:
"SELECT Open//? FROM tblJobList WHERE WeekEnding=?"
You can get something similar to your problem here:
Round bracket in string with JDBC prepared statement
Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.
I'm trying to build a web page to better learn Java and SQL. My question is, is there a way in Java to make a generic SQL select statement? For example:
SELECT var1 FROM var2 WHERE var3=var4
or something of the sort.
My idea is to fill the vars with user selected items from the web page. I know this can be done in PHP using the Post method, but I'm not using PHP. Also, I've read about the Prepared Statement in Java, but seems only to work when the used after the comparison operator; ex:
SELECT * FROM table Where attr = ? &
Also, I do know i can do the hard coded version of "SELECT " + var1 + "FROM " + var2 + "WHERE attr = " + var3 + " " but that doesn't seem very generic and prone to a lot of errors.
Incase: I'm trying to build this test page using HTML & JSP.
What you are doing with the ? is parameterizing the query. The query can only be parameterized for values not names of tables or columns.
Every time you run a query. The database has to create a query plan. If you are running the same query again and again, you can reduce this overhead by creating a PreparedStatement.
The first execution of PreparedStatement will generate the query plan. The subsequent executions will reuse the same plan.
Same query here means, it is identical in all respects except values used in where clause, expressions etc.
If you change the Column or Table name or modify the structure of the query, then it is a different query and will require a different query plan. A PreparedStement is not useful in this case and you should stick to the hardcoded version you talked about. Because of this reason you will get an error if you try to parameterize Table or Column names in PreparedStement.
Having said that. It is not advisable to take such a generic approach for queries. If your queries are that simple, you can benefit from ORM tools. You would not have to maintain even a line of SQL. For complex queries you have an option of using ORM specific query language or JPQL or Native SQL. Look for JPA + Hibernate
Your specific usage is not permitted by JDBC. You need to hard code the table name when creating the prepared statement. If you really do want to do that I suggest you use String concatenation to create the SQL statements and then create a PreparedStatement with parameters to handle the where part. In case you are wondering why bother with PreparedStatements in the specific solution, it's to avoid SQL injection.
You can use PreparedStatement to achive your objective.
For example -
String query = "SELECT * FROM table Where attr = ?";
PreparedStatement pt = con.prepareStatement(query);
pt.setString(1, attribete);
pt.executeUpdate();
There is no such direct provision in any of SQL packaged classes or others to replace table, column names along with query parameter values, in a query string, using a single method.
You require to depend on both PreparedStatement and any of String methods replace(...) and replaceFirst(...) to achieve your requirement.
String sql = "Select $1, $2 from $3 where $4=? and $5=?";
sql = sql.replaceFirst( "$1", "col1_name" );
sql = sql.replaceFirst( "$2", "col2_name" );
sql = sql.replaceFirst( "$3", "table_name" );
sql = sql.replaceFirst( "$4", "col4_name" );
sql = sql.replaceFirst( "$5", "col5_name" );
// .. and so on
PreparedStatement pst = con.prepareStatement( sql );
// use relevant set methods to set the query parametrs.
pst.setXXX( 1, value_for_first_query_parameter ); // from a variable or literal
pst.setXXX( 2, value_for_second_query_parameter); // from a variable or literal
// ... and so on
If you are using JDBC, can try this
PreparedStatement statement = connection.prepareStatement("SELECT ? FROM ? WHERE ?=? ");
then
statement.setString(1, "column_name");
statement.setString(2, "table_name");
statement.setString(3, "column_name");
statement.setBigDecimal(4, 123);
If you are using other ORM like Hibernate or JPA, I believe there are also ways to do.