bubblebath
bubblebath

Reputation: 999

Java string as text variable

I am trying to insert a bit of text into my MYSQL database via java.

the variable I am trying to put it into is a TEXT variable. My problem is that when I try to insert it, it picks up on the ' and thinks that it is a messed up insertion.

Here is the insert:

INSERT INTO TermsAndConditions (name,description,ownerID)  VALUES  ('bar condtions','Don't be stealin my stuff','2')

it thinks that by me having the word "Don't" is messed up

What I want to do is to do as little work as possible and tell the string just accept that all the characters need (their will probs be more than just the ' ) to have a "\'" or "\£" before them.

I know I can use replace but for ALL the characters would be a real pain! I am asking because their must be another simpler solution!

Thanks

Upvotes: 1

Views: 1683

Answers (5)

hsanders
hsanders

Reputation: 1923

Have you tried using prepared statements? The problem here is a matter of escaping Strings properly. Prepared statements can handle that for you and reduce unclean and ugly concatonation code.

http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Upvotes: 1

Kevin Mangold
Kevin Mangold

Reputation: 1155

You should use a PreparedStatement to escape your special characters.

Upvotes: 2

nybbler
nybbler

Reputation: 4841

Your best bet will likely to be use prepared statements (which is a good idea on it's own if you're not controlling the input for the insert to avoid sql injection!)

This site provides an example of how to do it: http://www.exampledepot.com/egs/java.sql/InsertPs.html

For your example, it would be something like:

// Prepare a statement to insert a record
String sql = "INSERT INTO TermsAndConditions (name,description,ownerID)  VALUES  (?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(sql);

// Set the values
pstmt.setString(1, "bar condtions");
pstmt.setString(2, "Don't be stealin my stuff");
pstmt.setString(3, "2");

// Insert the row
pstmt.executeUpdate();

Upvotes: 3

Mike Brant
Mike Brant

Reputation: 71384

You need to escape the single quote like this:

INSERT INTO TermsAndConditions (name,description,ownerID)  VALUES  ('bar condtions','Don\'t be stealin my stuff','2')

Upvotes: -1

karakuricoder
karakuricoder

Reputation: 1075

You need to escape the single quote or, better still, use prepared statements.

Upvotes: 2

Related Questions