jdbcTemplate是spring为我们提供的一个操作数据库的模板类,其实就是对JDBC做了一层薄薄的封装。
使用它我们需要先导入这几个包:
spring-jdbc-4.2.4.RELEASE.jar、spring-orm-4.2.4.RELEASE.jar、spring-tx-4.2.4.RELEASE.jar以及数据库驱动包
然后我们可以这么用:
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/test");
ds.setUsername("root");
ds.setPassword("root");
JdbcTemplate jt = new JdbcTemplate(ds);
jt.execute("insert into user values (2,'tom',6)");
或者我们将其放到容器中随时可以取出来用:
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="ds">
</constructor-arg>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jt");
jt.execute("insert into user values (2,'tom',6)");
CRUD:
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jt");
jt.update("insert into user values (?,?,?)", 3,"Jack",9);
jt.update("update user set name = ?,age=? where id = ?","Frank",8,3);
jt.update("delete from user where id = ?",3);
//查询所有
List<User> users = jt.query("select * from user where age>?", new BeanPropertyRowMapper<User>(User.class), 1);
for(User user : users){
System.out.println(user);
}
//查询一个
List<User> user = jt.query("select * from user where id = ?", new BeanPropertyRowMapper<User>(User.class), 1);
System.out.println(user.isEmpty() ? "没有数据":user.get(0));
//查询返回值是一行一列的情况
Integer count = jt.queryForObject("select count(*) from user where id > ?", Integer.class, 1);
System.out.println(count);