Spring中的jdbcTemplate操作
阿新 • • 發佈:2018-11-03
Spring中的jdbcTemplate操作
準備工作
1.設定資料庫資訊
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/ssm");
dataSource.setUsername("root");
dataSource.setPassword("root");
2.建立jdbcTemplate物件,設定資料來源
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
測試crud
1.add
public void add() {
String sql = "insert into user(username,password,sex,address) values(?,?,?,?)";
jdbcTemplate.update(sql, "令狐沖", "123", "男", "華山");
}
2.delete
String sql = "delete from user where userId = ?" ;
jdbcTemplate.update(sql, 2);
3.update
String sql = "update user set password = ? where userId = ?";
jdbcTemplate.update(sql, "lhc", 3);
4.select
4.1 查詢有多少條資料:
public Integer selectNum() {
String sql = "select count(*) from user";
//第二個引數是返回型別
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
4.2 查詢返回物件
public User selectUser() {
String sql = "select * from user where userId = ?";
//需要自己寫一個繼承RowMapper介面的實現類
User user = (User) jdbcTemplate.queryForObject(sql, new MyRowMapper(), 3);
return user;
}
class MyRowMapper implements RowMapper{
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
//從結果集中拿到資料
String userId = resultSet.getString("userId");
String username = resultSet.getString("username");
String password = resultSet.getString("password");
String sex = resultSet.getString("sex");
String address = resultSet.getString("address");
//把得到的資料封裝到物件中
User user = new User();
user.setUserId(Integer.valueOf(userId));
user.setUsername(username);
user.setPassword(password);
user.setSex(sex);
user.setAddress(address);
return user;
}
}
4.3 查詢返回list
public List<User> selectUserList() {
String sql = "select * from user";
List<User> list = jdbcTemplate.query(sql, new MyRowMapper());
return list;
}