1

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

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

2 回答 2

2

将 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 攻击,而是参数化您的值。

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 方法设置值。

你可以在这里阅读教程

于 2012-04-26T03:52:05.177 回答
0

您可以使用以下查询进行不区分大小写的搜索。

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());
于 2012-05-02T11:11:35.840 回答