如何将从数据库获取的值分配给标签?
问题描述:
我需要将查询从数据库中获取的字符串分配给Jlabel。我尝试了很多方法但失败了。我该怎么做?如何将从数据库获取的值分配给标签?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
答
需要研究的步骤,通过使用ResultSet对象调用ResultSet rs = pst.execute();
迭代通过行的名单,以连接到数据库在Java中首先 获取从statment结果集。 之后,将值分配给JLabel。
答
你只是在你的小程序提出了一些错误,看看下面的代码为例:
// 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
从不将您的将参数直接查询到您的SQL字符串中,这会打开SQL注入的代码。改为使用[PreparedStatement](http://www.tutorialspoint.com/javaexamples/jdbc_prepared_statement.htm)。 – CubeJockey
你在哪里给标签赋值? –
JLabel在这里无关紧要。你真的只是问你如何从jdbc调用中获得价值。 – ergonaut