简体   繁体   中英

Java+SQL executeQuery and return results

I'm new to java and I have this problem when I'm trying to fetch data from SQL DB and show it when he logs in.

sql = "select nom from adherent where id_adherent=3";
try {
    pst = con.prepareStatement(sql);
    ResultSet rs = pst.executeQuery();
} catch (SQLException e) {
    JOptionPane.showMessageDialog(null, "here 1");
}

try {
    if (rs.next()) {
        String sum = rs.getString("select *");
        nom.setText(" " + sum);
    }
} catch (SQLException e) {
    JOptionPane.showMessageDialog(null, "here 2");
}

Thank You.

Your don't need two try and catch, because you define your ResultSet in the first try block, so you can't use this, in another try, so make this instead :

sql = "select nom from adherent where id_adherent=3";
try {
    pst = con.prepareStatement(sql);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        String sum = rs.getString("nom");
        nom.setText(" " + sum);
    }
} catch (SQLException e) {
    JOptionPane.showMessageDialog(null, "here 1");
}

If you want something perfect and far of any syntax error, or SQL Injection, you have to use the operator ? of PreparedStatement for example :

sql = "select nom from adherent where id_adherent = ?";
//--------------------------------------------------^
try {
    pst = con.prepareStatement(sql);
    pst.setInt(1, id_adherent);//you can set any number in id_adherent in your case 3
    ....

I think this will help you:

sql = "select nom from adherent where id_adherent=3";

try {
    pst = con.prepareStatement(sql);
    ResultSet rs = pst.executeQuery();

    if (rs.next()) {
        String sum = rs.getString("nom");
        nom.setText(" " + sum);
    }  
}
catch (SQLException e) {
    JOptionPane.showMessageDialog(null, "here 1");
}

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