先导包
spring-jdbc、spring-tx、mysql驱动包,具体的自己去下载或者搜索
增加
- 创建对象,设置数据库
DriverManagerDataSource datasource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxxxx");
- 创建jdbcTemplate对象,设置数据源
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "insert into t_user values(?,?);
- 调用jdbcTemplate对象里面的方法实现操作
//更新的行数
int row = jdbcTemplate.update(sql,"xxx","xxx");
System.out.println(row);
修改
@Test
public void update(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxxxx");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "update t_user set password=? where username=?";
int row = jdbcTemplate.update(sql,"456789","TiHom");
System.out.println(row);
}
删除
@Test
public void delete(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxxxx");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "delete from t_user where username=?";
int row = jdbcTemplate.update(sql,"TiHom");
System.out.println(row);
}
查询
- 查询返回对象
@Test
public void search(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxxxx");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "select * from t_user where username=?";
//第二个参数需要自己实现接口实现类,自己做数据封装
User user = jdbcTemplate.queryForObject(sql,new MyRowMapper(),"TiHom");
System.out.println(user);
}
MyRowMapper实现类
class MyRowMapper implements RowMapper<User>{
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
//从结果集中获取数据
String username = resultSet.getString("username");
String password = resultSet.getString("password");
User user = new User();
//将数据封装到对象里面
user.setUsername(username);
user.setPassword(password);
return user;
}
}
- 查询返回list集合
只需改动一处
String sql = "select * from t_user";
List<User> list = jdbcTemplate.query(sql,new MyRowMapper());