如何使用sql2o访问和打印数据

时间:2015-11-16 21:35:59

标签: java mysql jdbc

所以我的代码块类似于:

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

(还有一个getID方法和getDesc方法遗漏了) 我可以运行这样的东西来获取它返回的列表中的对象:

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

如果我试着像这样打印id或desc

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

我总是得0和null,这不是正确的值。我需要做些什么才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

如果您只想打印SQL结果,可以通过调用executeAndFetchTable()并迭代返回的org.sql2o.data.Table对象。以下是示例代码:

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