I want to store a string containing '\n' in Sql using Java. But the problem is in the database instead of \n a new line is getting stored.
e.g the string is "abcd\nefgh" then the database it is getting stored as
abcd
efgh
I had the same issue when i was storing such things using php i overcame that using mysqli_escape_real_string()
How can i overcome this problem in java? please help.
But the problem is in the database instead of \n a new line is getting stored.
Well it sounds like the string itself probably contains a newline. If you write:
String x = "a\nb";
in Java, then that is a string with 3 characters:
That should be stored as a string of 3 characters in the database. When you fetch it back, you'll faithfully get a string of 3 characters back. The database will simply store what you give it.
Now if you're saying that you're trying to store a string which actually contains a backslash followed by an n
, and that is being converted to a newline somewhere, then you'll need to post some code to show what you're doing. For example, I could imagine that might happen if you're including the value directly in your SQL statement instead of using parameterized SQL. (Always use parameterized SQL.)
So basically, either it's actually not a problem at all, or you should post some code.
EDIT: Now we've seen this:
I had the same issue when i was storing such things using php i overcame that using mysqli_escape_real_string()
It sounds like maybe you are just facing a problem of inappropriate inclusion of values in a SQL statement. If you're using something like:
String sql = "INSERT INTO TABLE FOO VALUES ('" + text + "')";
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
then you need to stop doing that. You should use:
String sql = "INSERT INTO TABLE FOO VALUES (?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, text);
statement.execute();
(With appropriate code for closing the statement and connection, e.g. the try-with-resources statement in Java 7.)
See more on this question at Stackoverflow