publicclassTestJdbcTemplate{@Testpublicvoidtest01(){//创建数据源对象 四大信息
DriverManagerDataSource dataSource=newDriverManagerDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
dataSource.setUsername("root");
dataSource.setPassword("123456");//JdbcTemplate对象 update 增删改
JdbcTemplate jdbcTemplate =newJdbcTemplate(dataSource);//参 数据源连接池//调用update
jdbcTemplate.update("insert into stu values(?,?,?,?)",1000,"jack","吉首",100);//参1 sql,参2 占位符对应的参数}}
applicationContext.xml
<!-- DriverManagerDataSource dataSource = new DriverManagerDataSource();--><!-- dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");--><!-- dataSource.setUsername("root");--><!-- dataSource.setPassword("123456");--><beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><propertyname="url"value="jdbc:mysql://localhost:3306/springjdbc"/><propertyname="username"value="root"/><propertyname="password"value="123456"/></bean><!-- //JdbcTemplate对象 update 增删改--><!-- JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);//参 数据源连接池--><beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><constructor-argname="dataSource"ref="dataSource"/></bean>
TestJdbcTemplateSpring
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")publicclassTestJdbcTemplateSpring{//什么时候使用注解 ,如果是自己开发的类,使用注解//如果是别人开发的,因为注解加不上去,使用xml@Autowired
JdbcTemplate jdbcTemplate;@Testpublicvoidtest01(){//调用update
jdbcTemplate.update("insert into stu values(?,?,?,?)",1000,"rose","吉首",100);//参1 sql,参2 占位符对应的参数}@Testpublicvoidtest02(){//调用update
jdbcTemplate.update("delete from stu where sid = ? ",1000);//参1 sql,参2 占位符对应的参数}@Testpublicvoidtest03(){//调用update
jdbcTemplate.update("update stu set sname = ? where sid= ?","关于",17);//参1 sql,参2 占位符对应的参数}}
//返回结果是一个值或者一个行 queryForObject@Testpublicvoidtest04(){// Integer count= jdbcTemplate.queryForObject(" select count(*) from stu;",Integer.class);// System.out.println(count);// String name =jdbcTemplate.queryForObject("select sname from stu where sid=?;",String.class,17);//参1 sql// System.out.println(name);
String sql ="select * from stu where sid=?;";//一行数据转换成一个对象需要rowmapper
BeanPropertyRowMapper rowMapper =newBeanPropertyRowMapper(Stu.class);
Stu s =(Stu) jdbcTemplate.queryForObject(sql,rowMapper,17);//参1 sql 参2 RowMapper 参3 赋值
System.out.println(s);// Map<String,Object> map = jdbcTemplate.queryForMap(sql,17);//参1 sql 参3 赋值// System.out.println(map.get("sid"));}