import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class StudentDao {
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedJdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
public void setNamedJdbcTemplate(NamedParameterJdbcTemplate namedJdbcTemplate){
this.namedJdbcTemplate = namedJdbcTemplate;
}
//使用索引参数
public void addStudent(Student student){
String sql = "INSERT INTO student values(?,?,?)";
jdbcTemplate.update(sql,student.getId(), student.getAge(),student.getName());
}
//使用命名参数
public void addStudent2(Student student){
Map<String, Object> params = new HashMap<String, Object>();
params.put("id", student.getId());
params.put("age", student.getAge());
params.put("name", student.getName());
//使用命名参数,不是传统的索引参数,命名参数通过map进行绑定
String sql = "insert into student values(:id, :age,:name)";
namedJdbcTemplate.update(sql, params);
}
public Student getStudent(int id){
String sql = "select id,age,name from student where id = ?";
return jdbcTemplate.queryForObject(sql, new RowMapper<Student>(){
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student s = new Student();
s.setId(rs.getInt("id"));
s.setAge(rs.getInt("age"));
s.setName(rs.getString("name"));
return s;
}
},
id);//参数绑定
}
}
Spring jdbcTemplat插入,查询
最新推荐文章于 2023-12-01 08:04:09 发布