c3p0作为演示
1.编写资源文件(db.properties)
jdbc.user=rootjdbc.password=rootjdbc.jdbcUrl=jdbc:mysql://localhost:3306/springjdbc.driverClass=com.mysql.jdbc.Driver
2.在SpringXML配置中获取数据源资源文件
3.配置c3p0的连接参数
4.配置spring的jdbcTemplale bean
到这里数据源已经配置好了,直接获取bean就可以使用了。
案例:
修改前的数据:
修改后的数据:
操作代码:
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");String sql = "update tb_student set name='lisi' where id=2 ";jdbcTemplate.update(sql);
其他的操作和原生jdbc没什么太大区别。
配置NamedParameterJdbcTemplate只需要通过构造注入dataSource就OK
操作代码:
NamedParameterJdbcTemplate jdbcTemplate = (NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate"); String sql = "update tb_student set name=:name where id=:id "; Mapmap = new HashMap(); map.put("name","lisi2"); map.put("id",2); jdbcTemplate.update(sql, map);