使用ResultSet.getString检查重复项

时间:2015-02-07 08:31:25

标签: java sql jsp resultset duplicate-data

我可以通过检查数据库中是否有重复项来了解验证变量的最佳方法吗?

我已经尝试过几种不同的方式,但只要第一个if条件未满足,就会显示空白页

修改:我已考虑将username设置为唯一值,但这会与我的主键staff_id

发生冲突
<%-- Checking for duplicates - Reading --%>
<%
if(request.getParameter("Check") != null){
        try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        String conURL1= "jdbc:odbc:HOD_DATA";
        Connection con1 = DriverManager.getConnection(conURL1);
        Statement st1 = con1.createStatement();
        String query = "select username from Staff where username = '"+sUsername+"'";
        ResultSet rs = st1.executeQuery(query);

        while(rs.next()){
        result = rs.getString("username");

        if(result.equals(sUsername)) {
        response.setHeader("Refresh", "3; URL=StaffReg.jsp");   
        out.println("You may not use this username.");

        }

        else if(rs.wasNull()) { 
        response.setHeader("Refresh", "3; URL=StaffReg.jsp");
        out.println("You may use this username.");

        }


        }
        rs.close();
        st1.close();
        con1.close();
        }

        catch(Exception e){
        out.println(e);
        }
}

        %>

1 个答案:

答案 0 :(得分:0)

您可以获取计数并检查是否计数&gt; 0

这是一个例子。希望这会有所帮助。

public int checkUsername(String sUsername) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count =0;
        try{
            conn = DatabaseManager.con();
            String query="select count(*) from Staff where username=? ";
            pstmt=conn.prepareStatement(query);
            pstmt.setString(1,sUsername);
            rs=pstmt.executeQuery();

            while (rs.next()) {
                count=rs.getInt("count(*)");

            }

        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally {
            if (rs != null)
                DatabaseManager.rs_close(rs);
            if (pstmt != null)
                DatabaseManager.stmt_close(pstmt);
            if (conn != null)
                DatabaseManager.con_close(conn);
        }
        return count;

    }

//调用方法并检查。

if(checkUsername("Amanda")>0 ){

                System.out.println("user exists");


            }