首先创建一个表和与之对应的Bean类,表结构代码如下:
CREATE TABLE `demo` ( `id` int(11) DEFAULT NULL, `name` varchar(32) DEFAULT NULL ) ENGINE = InnoDB CHARSET = utf8; INSERT INTO demo VALUES (1, 'alan1'), (2, 'alan2'), (3, 'alan3'), (4, 'alan4'), (5, 'alan5');
Bean类代码如下:
public class Demo { private Integer id; private String name; public Demo() { } public Demo(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Demo{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
之后编写Java代码,使用DBUtils查询id大于2的所有记录,代码如下:
@Test public void testDBUtils() throws Exception { // 读取配置并获得连接 Properties properties = new Properties(); properties.load(new FileInputStream("src\\druid.properties")); DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); Connection connection = dataSource.getConnection(); QueryRunner queryRunner = new QueryRunner(); String sql = "select * from demo where id > ?"; // 执行SQL List<Demo> list = queryRunner.query(connection, sql, new BeanListHandler<>(Demo.class), 2); for (Demo demo : list) { System.out.println(demo); } connection.close(); }
运行结果为:
表 | JavaBean |
---|---|
int | Integer |
double | Double |
char | String |
varchar | String |
date | Date或String |