-1

我正在制作一个关于图书馆计算机座位监控的 java 程序。如果图书馆管理员输入学生的学号,他/她将被登录,他/她的名字和姓氏将显示在 java GUI 中的 JLabel 上。学号、名字和姓氏都在数据库中。我将如何从数据库中检索这些数据并将其存储到 JLabel 中?

4

2 回答 2

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 */ }
}
于 2012-09-30T02:15:16.870 回答
3

根据您对另一个答案的评论(+1 to logan),这里是一些伪代码,用于显示将结果存储在 a 中的逻辑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());
于 2012-09-30T02:24:37.567 回答