Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping an apostrophe in Java

I'm still somewhat new to Java and trying to insert data into a database. I'm getting an error when inserting a string containing 's so my end result would be to escape the apostrophe. How can I accomplish?

like image 292
somejkuser Avatar asked Aug 08 '26 12:08

somejkuser


2 Answers

Use prepared statements. As well as handling any special characters, they are much more robust and help prevent sql injection attacks.

like image 77
jqa Avatar answered Aug 11 '26 00:08

jqa


The issue really isn't with Java, rather with the underlying database. Most likely you are stringing your parameters together like this:

  String sql = "select * from sometable where somefield = " + someObject.getSomeField();

Don't do that. Use PreparedStatement's instead.

That has the added advantage of preventing SQL injection attacks, if this is an application that has to be concerned about such things.

like image 36
Yishai Avatar answered Aug 11 '26 01:08

Yishai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!