我如何使用 sql2o 访问和打印数据
How do i access and print out data with sql2o
所以我有类似于这样的代码块:
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方法省略)
我能够 运行 像这样获取列表中的对象 returns:
Task myTask1 = Task.getAllTasks().get(0);
如果我尝试像这样打印 id 或 desc
System.out.println(myTask1.getID());
System.out.println(myTask1.getDesc());
我总是得到 0 和 null,这不是正确的值。我需要做什么才能让它工作?
如果您只想打印 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")));
}
}
}
所以我有类似于这样的代码块:
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方法省略) 我能够 运行 像这样获取列表中的对象 returns:
Task myTask1 = Task.getAllTasks().get(0);
如果我尝试像这样打印 id 或 desc
System.out.println(myTask1.getID());
System.out.println(myTask1.getDesc());
我总是得到 0 和 null,这不是正确的值。我需要做什么才能让它工作?
如果您只想打印 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")));
}
}
}