如何使用PreparedStatement和Case INsensitive搜索

时间:2012-04-26 03:47:20

标签: java postgresql prepared-statement case-insensitive

1.如何将PrepareStatement用于姓氏和名字?
2.另外,如何通过familyname或givenname进行不区分大小写的搜索?

String query ="SELECT agent.familyname, agent.givenname" +
                    " FROM agent" +
                    " WHERE agent.agentid = piececreation.agentid" +
                    " AND (LOWER(familyname) = '"+agent_lastname+"' OR LOWER(givenname) = '"+agent_name+"') ORDER by familyname";


            PreparedStatement pst = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
            pst.setString(1, agent_lastname);
            pst.setString(2, agent_name);
            // Executing the insert
            pst.executeUpdate();

2 个答案:

答案 0 :(得分:1)

将familyName或givenName设置为小写,因为您已经在使用LOWER DB API

String query ="SELECT agent.familyname, agent.givenname" +
                        " FROM agent" +
                        " WHERE agent.agentid = piececreation.agentid" +
                        " AND (LOWER(familyname) = '"+agent_lastname.toLowerCase()+"' OR LOWER(givenname) = '"+agent_name.toLowerCase()+"') ORDER by familyname";

当您使用PreparedStatement时,不要直接在SQL中附加值,如果您这样做,则很容易SQL Attack参数化您的值。

String query = 
                "SELECT agent.familyname, agent.givenname"
                + " FROM agent"
                + " WHERE agent.agentid = ?"
                + " AND (" 
                + " LOWER(familyname) = ? OR LOWER(givenname) = ?" 
                + ") " 
                + " ORDER by familyname";


        pst.setInt(1, piececreation.agentid);
        pst.setString(2, agent_lastname.toLowerCase());
        pst.setString(3, agent_name.toLowerCase());

然后设置调用适当的setXXX方法的值,如定义here

您可以阅读教程here

答案 1 :(得分:0)

您可以使用以下查询进行caseinsensetive搜索。

String query = 
                "SELECT agent.familyname, agent.givenname"
                + " FROM agent"
                + " WHERE agent.agentid = ?"
                + " AND (" 
                + " familyname ilike ? OR givenname ilike ?" 
                + ") " 
                + " ORDER by familyname";


        pst.setInt(1, piececreation.agentid);
        pst.setString(2, agent_lastname.toLowerCase());
        pst.setString(3, agent_name.toLowerCase());