views:

1039

answers:

2

Hi

I am trying to insert user's input in oracle using Java JDBC. I have to use Insert query.

Oracle's column type is varchar2.

I am able to insert if user is not entering special character. when user enter special character like # ? / and $ it gives exception

Please help to parse these special character. i need to use insert query i cant use stored procedure or callable statement in my project.

Thank you for your time.

+7  A: 

So far as I know Oracle doesn't require you to escape string values so:

INSERT INTO some_table (my_varchar_column) VALUES ('my string with a ?');

should work.

But to be sure use a java.sql.PreparedStatement as follows:

PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO some_table (my_varchar_column) VALUES (?)");
preparedStatement.setString(1, "my string with a ?");
preparedStatement.execute();

Using a prepared statement is generally the recommended way to execute SQL against a database. It will aid performance and help prevent SQL injection attacks.

Nick Holt
Hi Nick,Thanks for reply.u r right that oracle does not require escape string.. but when i am trying to insert ? through java .. it consider as parameter which is actually is part of string
Hi Ajay - please can you post your Java code. In both the examples I gave above, I think the driver should be dealing with any escaping that is needed.
Nick Holt
+1  A: 

The only character that needs escaping in a SQL string constant is the single quote, for the obvious reason that it could otherwise be confused for the end of the string.

If you are using JDBC PreparedStatement's, then a question mark by itself stands for a parameter. You would write something like

insert into mytable (field1, field2) values (?, ?)

and then use set statements to set these values. If you enclose the question mark in quotes, then it should just be another character in a string, i.e.

insert into mytable (field1, field2) values (?, '?')

has ONE parameter ? and one string literal '?'.

PreparedStatement.set will do the necessary escaping of quotes. If you build the query yourself, you'll need to include code to do that escaping. (Just double the quote, e.g.

insert into mytable (field1) values ('Bob said, ''Hello''')

Jay