Reputation: 59
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.
Upvotes: 0
Views: 1998
Reputation: 59950
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
....
Upvotes: 1
Reputation: 16
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");
}
Upvotes: 0