//1创建数据源(连接池)dbcp
BasicDataSource dataSource=new BasicDataSource();
//基本四项
dataSource.setDriverClassName("com.mysql.jdbc.Driver");//数据库驱动
dataSource.setUrl("jdbc:mysql://locahost:3306/test/person");//数据库地址
dataSource.setUsername("root");
dataSource.setPassword("root");
//2创建模板
JdbcTemplate jdbcTemplate=new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
//通过api操作
String insertSql="insert into person(id,user_name,password) values(?,?,?)";
jdbcTemplate.update(insertSql,1,"tom","123456");
//输出map以数据库中字段名为key {id=1, user_name=tom, password=123456}
String selectSql="select * from person where id =1";
Map<String, Object> map = jdbcTemplate.queryForMap(selectSql);
System.out.println(map);
//输出包含一个person的list
List<Person> personList = jdbcTemplate.query(selectSql, new RowMapper<Person>() {
@Override
public Person mapRow(ResultSet resultSet, int i) throws SQLException {
Person pseron = new Person();
pseron.setId(resultSet.getInt("id"));
pseron.setUserName(resultSet.getString("user_name"));
pseron.setPassword(resultSet.getString("password"));
return pseron;
}
});
for (Person person: personList) {
System.out.println(person);
}