5

I want to convert resultset to string. After that, I will use the string to write a html file.Course is a table contain courseid(String),name(String),prerequisites(String) connect database is ok. Here is my code and idea. Can you evaluate my idea or give me some better solution?

private static void printRecordFromCourse() throws SQLException {
    Connection dbConnection = null;
    Statement stmt = null;
    String printSQL = "SELECT * FROM course";

    try {
        dbConnection = getDBConnection();
        stmt = dbConnection.createStatement();
                    ResultSet rs=stmt.executeQuery(printSQL);
        while(rs.next()){
            //Retrieve by column name
            String courseid  = rs.getString("courseid");
            String name = rs.getString("name");
            String prerequisites = rs.getString("prerequisites");

            String result+ = "<tr><td>"+courseid+"</td><td>"+name+"</td><td>"+prerequisites"</td></tr>";
        }
        rs.close();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    } finally {
        if (stmt != null) {
            dbConnection.close();
        }
        if (dbConnection != null) {
            dbConnection.close();
        }
    }
}
7
  • 1
    Is there some error that you are getting with the above code? You can use a class - Course and use corresponding getter/setter methods to access/update the values Commented Sep 27, 2015 at 9:36
  • no I mean how to convert the resultset rs into String. My program work nỏmally Commented Sep 27, 2015 at 9:39
  • stackoverflow.com/questions/2317251/… Commented Sep 27, 2015 at 9:41
  • I wont recommend you calling toString directly on resultset. You should populate it in your Course class and define custom toString in your Course class which you can then call toString upon. Please ensure you add java tag to your question. Commented Sep 27, 2015 at 9:42
  • 1
    A ResultSet isn't a string, or anything resembling one. Logically speaking it is an array of maps. You need to traverse it, getting column values for each row, and do whatever you need to do with those. Commented Sep 27, 2015 at 9:43

2 Answers 2

5

You could use an ArrayList and store the columns in there, such as:

List allRows = new ArrayList();
    while(rs.next()){
        String[] currentRow = new String[numberColumns];
        for(int i = 1;i<=numberColumns;i++){
            row[i-1]=rs.getString(i);
        }
        rows.add(row);
    }

Your ArrayList now contains String arrays, where each array represents one row. Now you can simply transform the string array entries into strings, e.g. using Arrays.toString(allRows.get(i));

Sign up to request clarification or add additional context in comments.

1 Comment

How can you have a dynamic numberColumns?
2

I have not tried your code, but it looks workable at a glance.

Design-wise, we usually want to separate database access from other logic.

And likely you will want to define a class Course to hold this data and your business logic that operates on that data. For example, you may choose to implement a toHtmlTableRow method on Course that generates the HTML source. (In a more complex or sophisticated environment, you might also want to move that HTML-generation functionality to another class.) Something like this:

class Course {
    String id, name, prereq;

    public Course ( String id , String name , String prereq ) {
        this.id = id;
        this.name = name;
        this.prereq = prereq;
    }

    public CharSequence toHtmlTableRow () {
        StringBuilder html = new StringBuilder();
        html.append( "<tr>\n" );
        html.append( "<td>" + this.id + "</td><td>" + this.name + "</td><td>" + this.prereq + "</td>\n" );
        html.append( "</tr>\n" );
        return html;
    }

    // Override `Object`.
    @Override
    public String toString () {
        return "Course{ " +
        "id='" + id + '\'' +
        " | name='" + name + '\'' +
        " | prereq='" + prereq + '\'' +
        " }";
    }
}

Here is a complete working example app. For the sake of this demo, I crammed it all into a single .java file. In real work, I would not.

This example uses the H2 Database Engine. This example makes an in-memory database that never gets written to storage, again because this is a mere example.

Note the use of the try-with-resource & AutoCloseable syntax found in newer versions of Java to simplify working with JDBC.

package com.basilbourque.example;

import java.sql.*;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class DbToText {

    public static void main ( String[] args ) {
        DbToText app = new DbToText();
        app.doIt();
    }

    private void doIt () {

        try {
            Class.forName( "org.h2.Driver" );
        } catch ( ClassNotFoundException e ) {
            e.printStackTrace();
        }

        List< Course > courses = new ArrayList();

        try (
        Connection conn = DriverManager.getConnection( "jdbc:h2:mem:db_to_text" ) ;
        Statement stmt = conn.createStatement() ;
        ) {
            String sql = "CREATE TABLE course_ ( \n" +
            "  id_ VARCHAR NOT NULL PRIMARY KEY , \n" +
            "  name_ VARCHAR NOT NULL , \n" +
            "  prereq_ VARCHAR NOT NULL \n" +
            ");";
            stmt.execute( sql );

            // Insert row.
            sql = "INSERT INTO course_ ( id_ , name_ , prereq_ ) VALUES ( ? , ? , ? ) ;";
            try (
            PreparedStatement preparedStatement = conn.prepareStatement( sql ) ;
            ) {
                preparedStatement.setString( 1 , "C01" );
                preparedStatement.setString( 2 , "Course 1" );
                preparedStatement.setString( 3 , "None" );
                preparedStatement.executeUpdate();

                preparedStatement.setString( 1 , "C02" );
                preparedStatement.setString( 2 , "Course 2" );
                preparedStatement.setString( 3 , "C01" );
                preparedStatement.executeUpdate();

                preparedStatement.setString( 1 , "C03" );
                preparedStatement.setString( 2 , "Course 3" );
                preparedStatement.setString( 3 , "C02" );
                preparedStatement.executeUpdate();
            }

            // Query all.
            sql = "SELECT * FROM course_";
            try ( ResultSet rs = stmt.executeQuery( sql ) ; ) {
                while ( rs.next() ) {
                    //Retrieve by column name
                    String id = rs.getString( "id_" );
                    String name = rs.getString( "name_" );
                    String prereq = rs.getString( "prereq_" );

                    // Instantiate a `Course` object for this data.
                    Course c = new Course( id , name , prereq );
                    courses.add( c );
                }
            }
        } catch ( SQLException e ) {
            e.printStackTrace();
        }

        System.out.println( "List of courses: \n" + courses );

        System.out.println( "Courses as HTML table rows: " );
        for ( Course course : courses ) {
            System.out.println( course.toHtmlTableRow() );
        }
    }

    class Course {
        String id, name, prereq;

        public Course ( String id , String name , String prereq ) {
            this.id = id;
            this.name = name;
            this.prereq = prereq;
        }

        public CharSequence toHtmlTableRow () {
            StringBuilder html = new StringBuilder();
            html.append( "<tr>\n" );
            html.append( "<td>" + this.id + "</td><td>" + this.name + "</td><td>" + this.prereq + "</td>\n" );
            html.append( "</tr>\n" );
            return html;
        }

        // Override `Object`.
        @Override
        public String toString () {
            return "Course{ " +
            "id='" + id + '\'' +
            " | name='" + name + '\'' +
            " | prereq='" + prereq + '\'' +
            " }";
        }
    }
}

When run.

List of courses: 
[Course{ id='C01' | name='Course 1' | prereq='None' }, Course{ id='C02' | name='Course 2' | prereq='C01' }, Course{ id='C03' | name='Course 3' | prereq='C02' }]
Courses as HTML table rows: 
<tr>
<td>C01</td><td>Course 1</td><td>None</td>
</tr>

<tr>
<td>C02</td><td>Course 2</td><td>C01</td>
</tr>

<tr>
<td>C03</td><td>Course 3</td><td>C02</td>
</tr>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.