我正在制作一个关于图书馆计算机座位监控的java程序。如果图书馆保管人输入学生的学号,他/她将登录,他/她的名字和姓氏将显示在Java GUI中的JLabel上。学号,姓名和姓氏都在数据库中。我如何从数据库中检索这些数据并将其存储到JLabel?
答案 0 :(得分:4)
简单的事情是什么?使用JDBC
以下是该维基百科页面的示例:
Connection conn = DriverManager.getConnection(
"jdbc:mysql:myhostname1",
"myLogin",
"myPassword" );
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" );
try {
while ( rs.next() ) {
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
// Column numbers start at 1.
// Also there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
}
}
} finally {
try { rs.close(); } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
}
} finally {
try { stmt.close(); } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
}
答案 1 :(得分:3)
根据您对其他答案的评论(+1 to logan),这里有一些伪显示将结果存储在JLabel
中的逻辑:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM MyTable");
StringBuffer sb=new StringBuffer();//create string buffer to hold results
//use html to enable newlines in jlabel
sb.append("<html>");
while (rs.next()) {
sb.append(rs.getString("a")).append("<br>");//append results to buffer
}
sb.append("</html>");
//create label with results
JLabel label=new JLabel(sb.toString());
或者,您可以先创建JLabel
并在其实例上调用JLabel#setText(String text);
:
JLabel label=new JLabel();
//read results to buffer
label.setText(sb.toString());