importcom.imooc.sc.entity.Student;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.jdbc.core.JdbcTemplate;
importorg.springframework.jdbc.core.RowMapper;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.List;
importjava.util.Map;
publicclassTest {
privateJdbcTemplatejdbcTemplate;
{
ApplicationContextcontext=newClassPathXmlApplicationContext("spring.xml");
jdbcTemplate= (JdbcTemplate)context.getBean("jdbcTemplate");
}
publicvoidtestExecute(){
jdbcTemplate.execute("create table user1(id int,name varchar(20))");
}
publicvoidtestUpdate(){
Stringsql="insert into student(name,sex) values(?,?)";
jdbcTemplate.update(sql,newObject[]{"张飞","男"});
}
publicvoidtestUpdate2(){
Stringsql="update student set sex=? where id=?";
jdbcTemplate.update(sql,"女",1003);
}
publicvoidtestBatchUpdate(){
String[] sqls={
"insert into student(name,sex) values('关羽','女')",
"insert into student(name,sex) values('刘备','男')",
"update student set sex='女' where id=2001" };
jdbcTemplate.batchUpdate(sqls);
}
publicvoidtestBatchUpdate2(){
Stringsql="insert into selection(student,course) values(?,?)";
List<Object[]>list=newArrayList<Object[]>();
list.add(newObject[]{1005,1001});
list.add(newObject[]{1005,1003});
jdbcTemplate.batchUpdate(sql,list);
}
publicvoidtestQuerySimple1(){
Stringsql="select count(*) from student";
intcount=jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println(count);
}
publicvoidtestQuerySimple2(){
Stringsql="select name from student where sex=?";
List<String>names=jdbcTemplate.queryForList(sql,String.class,"女");
System.out.println(names);
}
publicvoidtestQueryMap1(){
Stringsql="select * from student where id = ?";
Map<String,Object>stu=jdbcTemplate.queryForMap(sql,1003);
System.out.println(stu);
}
publicvoidtestQueryMap2(){
Stringsql="select * from student";
List<Map<String,Object>>stus=jdbcTemplate.queryForList(sql);
System.out.println(stus);
}
publicvoidtestQueryEntity1(){
Stringsql="select * from student where id = ?";
Studentstu=jdbcTemplate.queryForObject(sql, newStudentRowMapper(), 1004);
System.out.println(stu);
}
@org.junit.TestpublicvoidtestQueryEntity2(){
Stringsql="select * from student";
List<Student>stus=jdbcTemplate.query(sql,newStudentRowMapper());
System.out.println(stus);
}
privateclassStudentRowMapperimplementsRowMapper<Student>{
publicStudentmapRow(ResultSetresultSet, inti) throwsSQLException {
Studentstu=newStudent();
stu.setId(resultSet.getInt("id"));
stu.setName(resultSet.getString("name"));
stu.setSex(resultSet.getString("sex"));
stu.setBorn(resultSet.getDate("born"));
returnstu;
}
}
}