简体   繁体   中英

Java Oracle insert Query

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.

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.

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, ie

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, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM