Java Insert Special Character & to MySQL Database

How to insert the "logical and" (&) to MySQL database?

You may try to escape the "&" character, but it doesn't work.


I was trying to read all strings line by line from txt file to MySQL database. Some string contains "&".
I did the following:

Statement sta = conn.createStatement();
String sql = "INSERT INTO  `phd`.`School` (`SchoolName` )VALUES ( '"+aLine.trim()+"');";
sta.execute(sql);

Then I tried to escape "&" by using the StringEscapeUtils class from Apache's commons. It didn't work.

Actually the problem can be solved with PreparedStatement class. The prepared statement not only can handle such escape problem, but also can efficiently execute the statement multiple times.

PreparedStatement st = db.conn.prepareStatement("INSERT INTO  `phd`.`School` (`SchoolName` )VALUES ( ?);");
st.setString(1, aLine.trim());
st.executeUpdate();
Category >> Database  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • libbi

    can you send the complete program in java for this