简体   繁体   English

如何检查mysql中的id是否已经存在于java中

[英]how to check if id in mysql already exists with java

I want to check if my id is already exist or not: 我想检查我的id是否已经存在:

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 一个用于checking the id exists or not
  2. and another for insert section . 另一个用于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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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