0

在我的项目中,我需要查询一个 id(由用户输入)是否存在,如果存在则显示“一切就绪”,否则显示“不存在数据”

请帮助我...在此先感谢。

          try
        {
            stmt = con.createStatement();
            rs = stmt.executeQuery("select accno from newCatalogue");

            while(rs.next())
            {
                int i = rs.getInt("accno");

                if(accno.equals(i))
                {
                    out.println("got it");
                }
                else
                {
                    out.println("no....!"); 
                }

            }
        }
        catch (Exception e) 
        {
            e.printStackTrace();

        }
4

2 回答 2

1

以下可能有效

try
{
 PreparedStatement pstmt = conn.prepareStatement("select accno from newCatalogue where accno = ?");
pstmt.setInt(1,input_accno);
ResultSet rs= pstmt.executeQuery();
if(rs.next())
  System.out.println("record found");
else
  System.out.println("record not found");
}

input_accno 是用户输入的id

于 2013-05-29T09:18:40.513 回答
0

您可以使用以下构造检查它。如果查询返回一行,则 id 已插入。

ResultSet rs = st.executeQuery(""select id from newCatalogue where accno='"+enterID+"'");
String id = "";
int affected_rows = 0;
while (rs.next()) {
    id = rs.getInt(1);
    affected_rows++;
}
if(affected_rows == 1) {
    return true;
} else {
    return false;
}

请注意,此示例对 SQL 注入不安全。

于 2013-05-29T09:20:46.780 回答