使用 ResultSet.getString 检查重复项

Checking for duplicates with ResultSet.getString

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

我已经尝试了几种不同的方法,但只要第一个 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);
        }
}

        %>

您可以获得计数并检查计数是否 > 0

这是一个 example.Hope 这会有所帮助。

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");


            }