Sid
Sid

Reputation: 1269

Escaping single quotes in JDBC with MySql

I have written code to store some headline's from news websites in a database. However the headlines also contain (') single quotes and double quotes from time to time and this causes an error when trying to insert it into the table.

What would be the best possible way to ge around this?

Here is my code:

Statement st = con.createStatement();
int val = st.executeUpdate("INSERT into imageinfo(imageurl,title,headline,website) VALUES('"+imageurl+"','"+title+"','"+headline+"','"+website+"')");

Upvotes: 2

Views: 2704

Answers (2)

JK.
JK.

Reputation: 5136

You should consider using Prepared Statements where your SQL queries are precompiled. Depending on where your data is coming from in the first place this may also guard against SQL Injections.

Another advantage of using prepared statements is that you can reuse the same statement with different parameters each time you execute it.

Upvotes: 4

Barranka
Barranka

Reputation: 21047

I think you can escape a character with the backslash (within the sql instruction)...

Another way is to enclose the values that contain single quotes with double quotes.

Upvotes: 0

Related Questions