准备好的声明不会逃避撇号

时间:2011-08-24 13:58:29

标签: java hibernate jdbc prepared-statement

我正在使用从hibernate获取的JDBC连接对象来执行bath更新,我这样做是因为我需要使用MySql ON DUPLICATE功能。但是,当试图插入时,我无法插入说字符串有特殊字符,

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();
}

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:9)

要转义单引号,您可以使用JDBC的转义序列。

Statement statement = 
statement.executeQuery(
  "SELECT * FROM DATA_TABLE  WHERE COLUMN1 LIKE 'Having\'s Quotes%' {escape '\'}");

{ escape '\'}通知JDBC驱动程序将'\'字符转换为特定于数据库的转义字符。

有用的链接here

另外,如果你使用PreparedStatement,你不必逃避!

PreparedStatment ps = conn.prepareStatement("SELECT * FROM DATA_TABLE WHERE COLUMN1 LIKE ?%");
ps.setString(1, "Having's Quotes");