2015-09-25 71 views
-1

我需要將查詢從數據庫中獲取的字符串分配給Jlabel。我嘗試了很多方法但失敗了。我該怎麼做?如何將從數據庫獲取的值分配給標籤?

try{ 
    String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' "; 
    pst=conn.prepareStatement(sql); 
    String x= (pst.execute()); 
} 
catch(Exception e){ 
} 
+1

從不將您的將參數直接查詢到您的SQL字符串中,這會打開SQL注入的代碼。改爲使用[PreparedStatement](http://www.tutorialspoint.com/javaexamples/jdbc_prepared_statement.htm)。 – CubeJockey

+0

你在哪裏給標籤賦值? –

+0

JLabel在這裏無關緊要。你真的只是問你如何從jdbc調用中獲得價值。 – ergonaut

回答

0

需要研究的步驟,通過使用ResultSet對象調用ResultSet rs = pst.execute(); 迭代通過行的名單,以連接到數據庫在Java中首先 獲取從statment結果集。 之後,將值分配給JLabel。

0

你只是在你的小程序提出了一些錯誤,看看下面的代碼爲例:

// your way of using prepared statement is wrong. 
    // use like this 
    String sql="SELECT MAX(allocationID) FROM allocation where unit=?;"; 
    Connection conn = getConnection(); 
    PreparedStatement ps = conn.prepareStatement(sql); 

    // assign values to the variables in the query string 
    ps.setString(1, dept); 

    // execute the query 
    ResultSet rst = ps.executeQuery(); 

    // parse the result set to get the value 
    // You'd better do some check here to ensure you get the right result 
    rst.next(); 
    String x = rst.getInt(1) + ""; 

    ps.close(); 
    conn.close(); 
} 

看一看的文章,如果你有興趣:https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html

+0

它工作。萬分感謝。當我從組合框中選擇不同的值時,能告訴我如何更改標籤中的值嗎?我應該嘗試一個循環嗎? – Oliver

相關問題