繁体   English   中英

使用 toString() 方法格式化结果集中的数据

[英]Formatting data from a result set with the toString() method

我的问题是,使用 toString 方法格式化 ResultSet 中的数据的最有效方法是什么?

这是我迄今为止的方法:

public void query()
{
    Statement stmt = null;
    ResultSet rs = null;

    try
    {
        //Create database connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/registrar",
                "abt1s", "abt1s");
        stmt = conn.createStatement();

        //create SQL statement
        String st = "SELECT * FROM  student WHERE studentID = '" + this.getStudentID() + " '";

        rs = stmt.executeQuery(st);

        String studentData = rs.toString();
        System.out.println(studentData);

        rs.close();
        stmt.close();
        conn.close();
    }catch(Exception e)
            {
                System.err.println("ERROR: Either cannot connect to the DB " + " or error with the SQL statement");
            }

}

您可以逐行浏览 ResultSet 并打印您想要的任何内容:

// Fetch each row from the result set
while (rs.next()) {
    // Get the data from the row using the column index
    String s = rs.getString(1);

    // Get the data from the row using the column name
    s = rs.getString("col_string");
}

您需要先将ResultSet转换为Student类,然后才能使用Student.toString生成正确的输出。

“从结果集中检索和修改值”解释了从ResultSet中提取数据的一种方法。

或者,您可以查看对象关系映射 (ORM),它可以简化从数据库行创建域对象(如Student )。 您更喜欢哪种 Java ORM,为什么? 对各种 ORM 的讨论以及如何开始使用它们提供了有用的指示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM