2

So i have code block similar to this:

public class Task {

private Long id;
private String description;
private Date dueDate;

// getters and setters here

public List<Task> getAllTasks(){
String sql =
    "SELECT id, description, duedate " +
    "FROM tasks";

try(Connection con = sql2o.open()) {
    return con.createQuery(sql).executeAndFetch(Task.class);
}
}
}

(There is also a getID method and getDesc method left out) I am able to run something like this to get the objects in the list it returns:

Task myTask1 = Task.getAllTasks().get(0);

If i try and print the id or desc from it like so

System.out.println(myTask1.getID());
System.out.println(myTask1.getDesc());

I always get 0 and null, which is not the correct values. What do i need to do to get this to work?

Big Rich
  • 5,864
  • 1
  • 40
  • 64
HashTables
  • 392
  • 2
  • 7
  • 22
  • Your code should work! Which database are you accessing? Did you try to loop over the result, instead of only printing the first value? – aaberg Nov 17 '15 at 14:17

1 Answers1

2

If you just want to print SQL result, it is possible by invoking executeAndFetchTable() and iterate the returning org.sql2o.data.Table object. Here is the sample code:

import org.junit.Test;
import org.sql2o.Connection;
import org.sql2o.Sql2o;

public class Sql2oTest {
    @Test
    public void testSql2oTable() {
        Sql2o sql2o = new Sql2o("jdbc:postgresql://10.9.8.7:5432/testdb", "utest", "password");
        try (Connection con = sql2o.open()) {
            con.createQuery("SELECT * FROM pg_catalog.pg_tables")
                .executeAndFetchTable()  // No entity class needed
                .rows()                  // List<org.sql2o.data.Row>
                .stream()                // Java 8 stream
                .forEach(row ->          // print what you want
                    System.out.println(row.getString(1) +
                        ", " + row.getObject(2) +
                        ", " + row.getObject("hasindexes")));
        }
    }
}
peihan
  • 592
  • 1
  • 8
  • 13