我是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");
}
谢谢。
答案 0 :(得分:1)
你不需要两次尝试捕捉,因为你在第一个尝试块中定义了ResultSet
,所以你不能在另一次尝试中使用它,所以请改为:
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注入,你必须使用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
....
答案 1 :(得分:0)
我认为这会对你有所帮助:
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");
}