2

所以我有类似这样的代码块:

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,这不是正确的值。我需要做什么才能让它工作?

4

1 回答 1

2

如果只想打印 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")));
        }
    }
}
于 2017-04-28T09:55:28.587 回答