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

标签 java jdbc

我的问题是,使用 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");
            }

}

最佳答案

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

// 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");
}

关于java - 使用 toString() 方法格式化结果集中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9223122/

相关文章:

java - 通过反射构造对象时如何传递各种参数?

java - 实现前获取JPanel的大小

Java JDBC 与 Eclipse 的连接

xml - 哪些关系数据库可以将 XML 存储为 native 类型?

java.sql : Validate ResultSet format

java - Postgres如何获取海量数据

java - 处理数据库:良好的软件工程概念

Java String to Date Conversion 抛出无法解析的日期

java - 如何在 Android 中将两个 8 位表示的字节转换为单个 16 位表示的整数值

Java继承和重写方法——修饰符的影响