Rajesh Hatwar
Rajesh Hatwar

Reputation: 1933

how can i check if the entry already exists in the table or not in servlet

in my project i have a requirement to enquire a id (entered by user) whether it exist or not if it exist then it show "all ready exist" other wise "no data exist"

please help me... thanks in advance.

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

        }

Upvotes: 0

Views: 5246

Answers (2)

sk2212
sk2212

Reputation: 1722

You can check it with following construct. If query returns a row the id is already inserted.

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;
}

Please note that this example is not safe against SQL injections.

Upvotes: 0

Pavan Kumar K
Pavan Kumar K

Reputation: 1376

The following might work

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 is the id entered by user

Upvotes: 1

Related Questions