我是java新手,当我尝试从SQL DB获取数据并在他登录时显示它时,我遇到了这个问题。
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");
}
谢谢。
最佳答案
你不需要两个try和catch,因为你在第一个try block 中定义了你的ResultSet
,所以你不能在另一个try中使用它,所以改为这样:
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");
}
<小时/>
如果你想要完美的东西,远离任何语法错误,或者SQL注入(inject),你必须使用PreparedStatement的运算符?
,例如:
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
....
关于Java+SQL执行查询并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43408938/