我需要将查询从数据库中获取的字符串分配给Jlabel。我尝试了很多方法但失败了。我该怎么办?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
答案 0 :(得分:0)
需要研究在Java中连接数据库的步骤首先db steps
通过调用ResultSet rs = pst.execute();
从声明中获取结果集
使用resultset对象遍历行列表。
之后,将值分配给JLabel。
答案 1 :(得分: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