Java 如何检查表中是否已经存在该条目
在我的项目中,我需要查询id(由用户输入)是否存在 如果存在,则显示“所有就绪存在”或“无数据存在” 请帮帮我。。。提前谢谢Java 如何检查表中是否已经存在该条目,java,jdbc,Java,Jdbc,在我的项目中,我需要查询id(由用户输入)是否存在 如果存在,则显示“所有就绪存在”或“无数据存在” 请帮帮我。。。提前谢谢 try { stmt = con.createStatement(); rs = stmt.executeQuery("select accno from newCatalogue"); while(rs.next()) {
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();
}
以下方法可能有效
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您可以使用以下结构检查它。如果查询返回一行,则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注入是不安全的。好的,那么到底出了什么问题?这可以用更好的方式来实现。但你到底需要什么帮助呢?