的Java + SQL的executeQuery和返回结果

的Java + SQL的executeQuery和返回结果

问题描述:

我新的Java和我有这个问题时,我想,当他登录到从SQL数据库获取数据并显示它。的Java + SQL的executeQuery和返回结果

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"); 
} 

谢谢。

+1

我怀疑'rs.getString(“select *”)'会有任何成功。 – Berger

+0

你不需要两个单独的try catch块,但是你的实际问题是什么? –

+0

只需按列名称(或索引)(如rs.getString(“nom”)或rs.getString(1))获取数据。另外,最好在您使用数据的同一个try块中使用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"); 
} 
+0

是的,我做了就像那谢谢@everyone

你并不需要两个try和catch,因为你在第一个try块定义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 
    .... 
+0

此外,当使用PreparedStatement时,将sql编写为“select by adherent where id_adherent =?”会更有意义(也更安全)。然后用pst.setInt(1,3)设置参数; –

+0

我已经在这方面写了一些东西@dsp_user只是片刻 –

+0

@dsp_user是你的意思检查我的编辑;) –