JdbcTemplate对jdbc进行了封装
1.导入jdbcTemplate使用的jar包
spring-jdbc-RELEASE.jar
spring-tx-RELEASE.jar
mysql-Connector-java.jar数据驱动
@Test
public void add(){
//设置数据库信息
DriverManagerDataSource dataSource = new DriverManagerSource();
dataSource.setDriverClassName("com.sql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///t_user");
dataSource.setUsername("root");
dataSource.setPassword("123456");
//创建jdbcTemplate对象,设置数据源
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//调用jdbcTemplate里面的方法实现操作
增加
String sql = "insert int user value(default,?,?)";
int rows = jdbcTemplate.update(sql,"lucy","1234");
System.out.println(rows);
删除
String sql = "delete from user where username=?";
int rows = jdbcTemplate.update(sql,"lucy");
查询
1 查询返回某一个值
String sql = "select count(*) from user";
int count = jdbcTemplate.queryForObject(sql,Integer.class);//类型的class
2 查询返回对象:queryForObject(String sql,RowMapper<T> rowMapper,Object..args)
在同一个类中写一个类:class MyRowMapper implements RowMapper<User>{
@Override
public User mapRow(ResultSet rs.int num) throws SQLException{
//
从结果集中得到结果
String username = rs.getString("username");
String password = rs.getString("password");
//把得到的数据封装到对象里面
User user = new User();
user.setName(username);
user.setPassword(password);
return user;
}
public class Demo{
........
String sql = "select * from user where username=?";
User user = jdbcTemplate.queryForObject(sql,new MyMapper());