简体   繁体   中英

how to check if id in mysql already exists with java

I want to check if my id is already exist or not:

sql2 = "SELECT stid FROM student";
stmt.executeUpdate(sql2);
rs = stmt.executeQuery(sql2);
    while(rs.next()){
        id = rs.getString("stid");
        if(tf_insert1.equals(id)){
        JOptionPane.showMessageDialog(null, "ID is already exists");
        id = tf_insert1.getText();
        name = tf_insert2.getText();
        address = tf_insert3.getText();
        gender = tf_insert4.getText();
        ip = tf_insert5.getText();
        tf_insert1.setText(id);
        tf_insert2.setText(name);
        tf_insert3.setText(address);
        tf_insert4.setText(gender);
        tf_insert5.setText(ip);

Any idea to solve this thing???

Please check this. I have modified code in 2 parts.

  1. One for checking the id exists or not
  2. and another for insert section .

Hope it will help to solve your issue.

private void yourFunction(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();

try {
    Connection con = util.getConnection();
    PreparedStatement stmt = con.prepareStatement(
        "SELECT stid FROM student where stid = ?");
    stmt.setLong(1, Long.parseLong(stid.getText()));      
    ResultSet rs=stmt.executeQuery();
    bool recordAdded = false;
    while(!rs.next()){            
         recordAdded = true;
    }
    if( recordAdded ){
      // your code for insertion.
    }else{
       JOptionPane.showMessageDialog(null, "ID is already exists");
    }
} catch (Exception ex) {
    Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM