java 准备好的语句不转义撇号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7176683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:57:33  来源:igfitidea点击:

Prepared Statement Not Escaping Apostrophe

javahibernatejdbcprepared-statement

提问by sesmic

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,

我正在使用从 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();
}

What could be causing this?

什么可能导致这种情况?

回答by Kal

To escape single quotes you can use JDBC's escape sequence.

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

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.

{ escape '\'}通知JDBC驱动程序翻译的'\'字符数据库特有的转义字符。

Helpful link here

有用的链接在这里

Also, if you use a PreparedStatement, you dont have to escape!

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

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