I am using JDBC connection object obtained from hibernate to perform bath update, I am doing this because I need to use the MySql ON DUPLICATE feature. But, when trying to insert I am not able to inset saying the string has special characters,
Session session = sessionFactory.openSession();
PreparedStatement pstm = null;
Connection conn = session.connection();
try
{
IRKeyWordTweet record = null;
conn.setAutoCommit(false);
for (Iterator itrList = statusToInsert.iterator(); itrList.hasNext();)
{
try
{
record = (IRKeyWordTweet) itrList.next();
pstm = (PreparedStatement) conn.prepareStatement("INSERT QUERY");
System.err.println(record.getTwtText());
//tweetId
pstm.setLong(1, record.getTweetId());
Setters For Prepared statement....
pstm.addBatch();
int[] updateCounts = pstm.executeBatch();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
catch (Exception e)
{
log.error("Exception Occured",e);
}
finally
{
try
{
pstm.close();
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
session.close();
}
What could be causing this?
Yes, you have to close the prepared statements ( PreparedStatement Object) and result sets as they may cause memory leakage.
The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query.
You can execute a given prepared statement multiple times, passing different variables to it or setting the variables to different values before each execution. For examples, see Section 13.5, “Prepared Statements”.
If you need to use single quotes and double quotes in a string that contains both a contraction and a quote, you will need to use the backslash '' to cancel out the following character.
To escape single quotes, you can use JDBC's escape sequence:
Statement statement =
statement.executeQuery(
"SELECT * FROM DATA_TABLE WHERE COLUMN1 LIKE 'Having\'s Quotes%' {escape '\'}");
The { escape '\'}
informs the JDBC driver to translate the '\'
character to the database-specific escape character.
Helpful link here
Also, if you use a PreparedStatement, you don't even have to escape!
PreparedStatement ps = conn.prepareStatement("SELECT * FROM DATA_TABLE WHERE COLUMN1 LIKE ?%");
ps.setString(1, "Having's Quotes");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With