-
Notifications
You must be signed in to change notification settings - Fork 12
InPureJDBC
Yong Zhu edited this page Mar 12, 2018
·
4 revisions
Below is an example shows by use jDialects's Pagination, Function translate and DDL output features:
public class TestDemo {
@Test
public void doTest() {
HikariDataSource ds = new HikariDataSource();// DataSource
// H2 is a memory database
ds.setDriverClassName("org.h2.Driver");
ds.setJdbcUrl("jdbc:h2:mem:DBName;MODE=MYSQL;DB_CLOSE_DELAY=-1;TRACE_LEVEL_SYSTEM_OUT=0");
ds.setUsername("sa");
ds.setPassword("");
Dialect dialect = Dialect.guessDialect(ds);
Dialect.allowLogOutput = true;
Connection conn = null;
try {
conn = ds.getConnection();
TableModel t = new TableModel("users");
t.column("firstName").VARCHAR(20).pkey();
t.column("lastName").VARCHAR(20).pkey();
t.column("age").INTEGER();
String[] ddlArray = dialect.toDropAndCreateDDL(t);
for (String ddl : ddlArray)
try {
execute(conn, ddl);
} catch (Exception e) {
}
for (int i = 1; i <= 100; i++)
execute(conn, "insert into users (firstName, lastName, age) values(?,?,?)", "Foo" + i, "Bar" + i, i);
Assert.assertEquals(100L, ((Number) queryForObject(conn, "select count(*) from users")).longValue());
List<Map<String, Object>> users = queryForMapList(conn, dialect.paginAndTrans(2, 10,
"select concat(firstName, ' ', lastName) as UserName, age from users where age>?"), 50);
Assert.assertEquals(10, users.size());
for (Map<String, Object> map : users)
System.out.println("UserName=" + map.get("USERNAME") + ", age=" + map.get("AGE"));
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
ds.close();
}
}
Above demoe can run on different databases, only need change the DataSource setting.
Full source code of the demo。