java - 不知道如何转换为字符串并打印 ResultSet、SELECT 语句

标签 java select jdbc resultset

这是我的一小段代码。基本上,我不知道如何打印我的结果集或将其转换为字符串。

try {
  String url = "jdbc:odbc:" + "userstuff"; 
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  Connection con = DriverManager.getConnection(url,"","");
  // Gets a statement
  Statement state = con.createStatement();
  String query = "SELECT description FROM topics WHERE title = '" + title + "'";
  String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";
  // selects the description for the selected topic ( title will be referenced to the chosen topic)
  ResultSet results = state.executeQuery(query);
  // selects * of the rows from "comment" table where the topic equals the selected title.
  ResultSet results2 = state.executeQuery(query2);
  desc = results.toString();
}

最佳答案

您不能将 ResultSet 转换为字符串,也不能直接从 ResultSet 打印。

以下代码可能会对您有所帮助。

try {
    String url = "jdbc:odbc:" + "userstuff"; 

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    Connection con = DriverManager.getConnection(url,"","");

    // Gets a statement
    Statement state1 = con.createStatement();
    Statement state2 = con.createStatement();

    String query1 = "SELECT description FROM topics WHERE title = '" + title + "'";

    // selects the description for the selected topic ( title will be referenced to the chosen topic)
    ResultSet results1 = state1.executeQuery( query1 );

    while( results.next() ){

        System.out.println( results1.getString( "description" );
    }

    // selects * of the rows from "comment" table where the topic equals the selected title.
    String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";

    ResultSet results2 = state2.executeQuery( query2 );

    while( results2.next() ){

        System.out.println( results2.getString( 1 ); // here 1 is tables 1st column
        System.out.println( results2.getString( 2 ); // here 2 is tables 2nd column
    }
} Exception( SQL e){

    e.printStackTrace();
}

关于java - 不知道如何转换为字符串并打印 ResultSet、SELECT 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41936595/

相关文章:

java - quartz 调度程序 : Maintain processed files list in the event job metadata

PHP MySQL UNION SELECT 未按预期方式工作

java - 为什么我的Oracle PreparedStatement有时即使没有争用也永远不会返回?

java - Netbeans 无法建立与 jdbc 的连接

java - 每个路径 Spring 多个 HandlerMethodArgumentResolver

java - 选择 JCheckBox 时添加到变量

java - logger.debug(...) 在日志文件中打印两次

mysql - 如何在 MySQL 中对从开始到指定日期的总计进行 SELECT?

mysql where 1= 0 混淆

java - 内部异常 : com. mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: