2017-04-14 92 views
1

我新的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。 –

回答

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

是的,我做了就像那謝謝@everyone <3 –

1

你並不需要兩個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是你的意思檢查我的編輯;) –