-1

我试图使用 Java 显示数据库中的行。我的想法是对数据库中的行进行排序并将它们显示在 3 列和无限行中。这就是我所拥有的。当我运行它时,我看不到任何输出。我哪里做错了?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException 
{
    Connection connection = null;
    try {
         Class.forName("com.mysql.jdbc.Driver");


        String url = "jdbc:mysql://localhost:3306/testapp";
        String user = "root";
        String password = "root";
        connection = DriverManager.getConnection(url, user, password);


        Statement stmt = connection.createStatement();
        String sql = "select * from site order by fname;";


        stmt.execute(sql);
    } catch (ClassNotFoundException e) {
        System.err.println("Could not load database driver!");
    } catch (SQLException e) {
        e.printStackTrace();
    } 
            finally 
            {
        if (connection != null) 
                    {
            connection.close();
        }
    }
}


}

我拥有的数据库表是 datas(id int, fname varchar(20)

4

2 回答 2

2
Statement stmt = connection.createStatement();
 String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);

while(rs.next()){
int id=rs.getInt("id");
.............
}

参考:从结果集中检索和修改值

于 2013-06-26T08:33:50.583 回答
0

代码应该获得 aResultsSet并遍历它。

    Class.forName("com.mysql.jdbc.Driver");

    String url = "jdbc:mysql://localhost:3306/testapp";
    String user = "root";
    String password = "root";
    connection = DriverManager.getConnection(url, user, password);


    Statement stmt = connection.createStatement();
    //You shouldn't need the semi-colon at the end
    String sql = "select * from site order by fname;";

    //missing piece
    ResultSet rs = stmt.executeQuery(sql);
    while (rs.next()) {

        int id = rs.getInt("id");
        String name = rs.getString("name");
        System.out.println(id + "\t" + name);
    }
于 2013-06-26T08:36:51.657 回答