JdbcTemplate的使⽤⼤全
1、判断数据库是否获得连接
@Test
public void test() throws SQLException {
DataSource bean = Bean(DataSource.class);
jdbctemplate查询一条数据Connection connection = Connection();
System.out.println(connection);
}
2、sql 语句的按位更新、或插⼊
@Test
public void test02(){
/
/1、从容器中获取JdbcTemplate进⾏操作
String sql = "update employee set salary=? where emp_id=?";
int update = jdbcTemplate.update(sql, 1300,5);
System.out.println(update);
}
3、sql 语句的批量插⼊
@Test
public void test03(){
String sql = "INSERT INTO `employee`(`emp_name`,`salary`) VALUES (?,?)";
List<Object[]> args = new ArrayList<>();
args.add(new Object[]{"张三",9989.98});
args.add(new Object[]{"李四",19989.98});
jdbcTemplate.batchUpdate(sql,args);
}
4、查询单个对象
数据字段与数据库相同
BeanPropertyRowmapper⽤来将javaBean属性和查出的数据⼀⼀映射
@Test
public void test04(){
String sql = "select * from employee where emp_id=?";
Employee employee = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Employee.class), 7); }
数据字段与数据库不同 需重写⽅法
public void test04(){
String sql = "select * from employee where emp_id=?";
Employee employee = jdbcTemplate.queryForObject(sql, new RowMapper<Employee >(){ @Override
public Employee mapRow(ResultSet rs, int index)throws SQLException {
Employee temp = new Employee ();
temp.Int("id"));
temp.String("name"));
return temp;
}
}, 7);
}
4-2、查询集合对象
@Test
public void test04(){
String sql = "select * from employee where emp_id=?";
List<helgolandLog> employees = jdbcTemplate.query(sql, new RowMapper<Employee >(){ @Override
public Employee mapRow(ResultSet rs, int index)throws SQLException {
Employee temp = new Employee ();
temp.Int("id"));
temp.String("name"));
return temp;
}
}, 7);
}
5、使⽤带有具名参数的SQL语句插⼊⼀条记录,并以Map形式传⼊参数值
@Test
public void test07(){
String sql = "INSERT INTO `employee`(`emp_name`,`salary`) VALUES (:empName,:salary)";
Map<String, Object> map = new HashMap<>();
map.put("empName", "韩总");
map.put("salary", 40000.0);
//如果⽀持具名参数的功能。JdbcTemplate就不能⽤了。
/*MapSqlParameterSource source = new MapSqlParameterSource(map);
namedTemplate.update(sql, source);*/
namedTemplate.update(sql, map);
}
6、以SqlParameterSource形式传⼊参数值
@Test
public void test08(){
String sql = "INSERT INTO `employee`(`emp_name`,`salary`) VALUES (:empName,:salary)";
Employee employee = new Employee(null, "韩五", 499998.00);
//如果⽀持具名参数的功能。JdbcTemplate就不能⽤了。
//SqlParameterSource
//BeanPropertySqlParameterSource
/
/可以直接将Bean的属性映射参数进⾏处理
namedTemplate.update(sql, new BeanPropertySqlParameterSource(employee));
}
7、⾃动装配 JdbcTemplate 对象
public void test09(){
EmployeeDao bean = Bean(EmployeeDao.class);
Employee employee = new Employee(null, "韩五11", 499998.00); bean.insert(employee);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论