1.Test class :
package com.bcsis.g3.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
public class JDBCTemplateTest {
static int addRecord(JdbcTemplate jdbc ) {
jdbc.execute(new ConnectionCallback() {
public Object doInConnection(Connection con) throws SQLException, DataAccessException {
String sql = "insert into TEST1(reason,volume, amount) values (?,?,?) ";
PreparedStatement ps = con.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "reason1");
ps.setInt(2, 100);
ps.setInt(3, 100);
ps.executeUpdate();
// ResultSet rs = ps.getGeneratedKeys();
// if (rs.next())
// user.setId(rs.getInt(1));
return null;
}
});
return 0;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext filecontext = new ClassPathXmlApplicationContext("com/bcsis/report/resources/JDBC-config.xml");
DataSource datasource = (DataSource) filecontext.getBean("dataSource");
System.out.println("datasource : "+datasource);
JdbcTemplate jdbc = new JdbcTemplate(datasource);
addRecord(jdbc);
}
}
2. xml config :
1)JDBC-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="datasource.xml" />
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
2.datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver.classname}" />
<property name="url" value="${db.connection.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
</beans>
Reference1 : http://lichaozhangobj.iteye.com/blog/700141
jdbcTemplate 例子
- public class JdbcTemplateTest {
- static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource());
- public static void main(String[] args) {
- }
- static int addUser(final User user) {
- //更灵活的使用connection
- jdbc.execute(new ConnectionCallback() {
- public Object doInConnection(Connection con) throws SQLException,
- DataAccessException {
- String sql = "insert into user(name,birthday, money) values (?,?,?) ";
- PreparedStatement ps = con.prepareStatement(sql,
- Statement.RETURN_GENERATED_KEYS);
- ps.setString(1, user.getName());
- ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
- ps.setFloat(3, user.getMoney());
- ps.executeUpdate();
- ResultSet rs = ps.getGeneratedKeys();
- if (rs.next())
- user.setId(rs.getInt(1));
- return null;
- }
- });
- return 0;
- }
- static Map getData(int id) {
- String sql = "select id as userId, name, money, birthday from user where id="
- + id;
- return jdbc.queryForMap(sql);
- }
- static String getUserName(int id) {
- String sql = "select name from user where id=" + id;
- Object name = jdbc.queryForObject(sql, String.class);
- return (String) name;
- }
- static int getUserCount() {
- String sql = "select count(*) from user";
- return jdbc.queryForInt(sql);
- }
- static List findUsers(int id) {
- String sql = "select id, name, money, birthday from user where id<?";
- Object[] args = new Object[] { id };
- int[] argTypes = new int[] { Types.INTEGER };
- List users = jdbc.query(sql, args, argTypes, new BeanPropertyRowMapper(
- User.class));
- return users;
- }
- static User findUser(String name) {
- String sql = "select id, name, money, birthday from user where name=?";
- Object[] args = new Object[] { name };
- Object user = jdbc.queryForObject(sql, args, new BeanPropertyRowMapper(
- User.class));
- return (User) user;
- }
- static User findUser1(String name) {
- String sql = "select id, name, money, birthday from user where name=?";
- Object[] args = new Object[] { name };
- Object user = jdbc.queryForObject(sql, args, new RowMapper() {
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- User user = new User();
- user.setId(rs.getInt("id"));
- user.setName(rs.getString("name"));
- user.setMoney(rs.getFloat("money"));
- user.setBirthday(rs.getDate("birthday"));
- return user;
- }
- });
- return (User) user;
- }
- }
- public class JdbcTemplateTest {
- public static JdbcTemplate jdbcTemplet = new JdbcTemplate(JdbcUtils
- .getDataSource());
- public static void main(String[] args) {
- }
- // 查询返回对象类型
- public static User getUser(String name) {
- String sql = "select id,name,password from user where name=?";
- Object[] args = new Object[] { name };
- Object user = jdbcTemplet.queryForObject(sql, args,
- new BeanPropertyRowMapper(User.class));
- return (User) user;
- }
- // 查询返回List类型
- @SuppressWarnings("unchecked")
- public static List<User> queryUserForList() {
- String sql = "select id,name,password from user";
- return jdbcTemplet.query(sql, new BeanPropertyRowMapper(User.class));
- }
- // 插入
- public static void insert() {
- String sql = "insert into user(name,password) values(?,?)";
- jdbcTemplet.update(sql, new Object[] { "wanger", "123456" });
- }
- // 删除
- public static void delete(int id) {
- String sql = "delete from user where id=?";
- jdbcTemplet.update(sql, new Object[] { 4 });
- }
- // 更新
- public static void update(User user) {
- String sql = "update user set name=?,password=? where id=?";
- Object[] args = new Object[] { "张三", "000000", 1 };
- int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR,
- Types.INTEGER };
- jdbcTemplet.update(sql, args, argTypes);
- }
- // 插入日期类型
- public static void insert2() {
- String sql = "insert into date_table(time) values(?)";
- Date date = new Date();
- Object[] args = new Object[] { date };
- // int[] argTypes = new int[] { Types.TIMESTAMP };
- // jdbcTemplet.update(sql, args, argTypes);
- jdbcTemplet.update(sql, args);
- }
- }
Reference2 :
Spring的JDBC框架能够承担资源管理和异常处理的工作,从而简化我们的JDBC代码,
让我们只需编写从数据库读写数据所必需的代码。Spring把数据访问的样板代码隐藏到模板类之下,
结合Spring的事务管理,可以大大简化我们的代码.
Spring提供了3个模板类:
JdbcTemplate:Spring里最基本的JDBC模板,利用JDBC和简单的索引参数查询提供对数据库的简单访问。
NamedParameterJdbcTemplate:能够在执行查询时把值绑定到SQL里的命名参数,而不是使用索引参数。
SimpleJdbcTemplate:利用Java 5的特性,比如自动装箱、通用(generic)和可变参数列表来简化JDBC模板的使用。
具体使用哪个模板基本上取决于个人喜好。
使用Spring的JdbcTemplate来实现简单的增删改查,首先建立测试数据表person
create table person(
id int not null primary key auto_increment,
name varchar(20) not null
)
导入依赖的jar包,由于测试中数据源使用的是dbcp数据源,需要以下jar包支持:
commons-logging.jar
commons-pool.jar
commons-dbcp.jar
同时还必须导入数据库驱动jar包:mysql-connector-java-3.1.8-bin.jar
建立实体bean
Person.java
- package com.royzhou.jdbc;
- public class PersonBean {
- private int id;
- private String name;
- public PersonBean() {
- }
- public PersonBean(String name) {
- this.name = name;
- }
- public PersonBean(int id, String name) {
- this.id = id;
- this.name = name;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String toString() {
- return this.id + ":" + this.name;
- }
- }
接口类:
PersonService.java
- package com.royzhou.jdbc;
- import java.util.List;
- public interface PersonService {
- public void addPerson(PersonBean person);
- public void updatePerson(PersonBean person);
- public void deletePerson(int id);
- public PersonBean queryPerson(int id);
- public List<PersonBean> queryPersons();
- }
实现类:
PersonServiceImpl.java
- package com.royzhou.jdbc;
- import java.util.List;
- import javax.sql.DataSource;
- import java.sql.Types;
- import org.springframework.jdbc.core.JdbcTemplate;
- public class PersonServiceImpl implements PersonService {
- private JdbcTemplate jdbcTemplate;
- /**
- * 通过Spring容器注入datasource
- * 实例化JdbcTemplate,该类为主要操作数据库的类
- * @param ds
- */
- public void setDataSource(DataSource ds) {
- this.jdbcTemplate = new JdbcTemplate(ds);
- }
- public void addPerson(PersonBean person) {
- /**
- * 第一个参数为执行sql
- * 第二个参数为参数数据
- * 第三个参数为参数类型
- */
- jdbcTemplate.update("insert into person values(null,?)", new Object[]{person.getName()}, new int[]{Types.VARCHAR});
- }
- public void deletePerson(int id) {
- jdbcTemplate.update("delete from person where id = ?", new Object[]{id}, new int[]{Types.INTEGER});
- }
- public PersonBean queryPerson(int id) {
- /**
- * new PersonRowMapper()是一个实现RowMapper接口的类,
- * 执行回调,实现mapRow()方法将rs对象转换成PersonBean对象返回
- */
- PersonBean pb = (PersonBean) jdbcTemplate.queryForObject("select id,name from person where id = ?", new Object[]{id}, new PersonRowMapper());
- return pb;
- }
- @SuppressWarnings("unchecked")
- public List<PersonBean> queryPersons() {
- List<PersonBean> pbs = (List<PersonBean>) jdbcTemplate.query("select id,name from person", new PersonRowMapper());
- return pbs;
- }
- public void updatePerson(PersonBean person) {
- jdbcTemplate.update("update person set name = ? where id = ?", new Object[]{person.getName(), person.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});
- }
- }
PersonRowMapper.java
- package com.royzhou.jdbc;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import org.springframework.jdbc.core.RowMapper;
- public class PersonRowMapper implements RowMapper {
- //默认已经执行rs.next(),可以直接取数据
- public Object mapRow(ResultSet rs, int index) throws SQLException {
- PersonBean pb = new PersonBean(rs.getInt("id"),rs.getString("name"));
- return pb;
- }
- }
我们需要在bean.xml中配置DataSource,并且将datasource注入到我们的业务类中
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
- <context:property-placeholder location="classpath:jdbc.properties"/>
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="${driverClassName}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- <!-- 连接池启动时的初始值 -->
- <property name="initialSize" value="${initialSize}"/>
- <!-- 连接池的最大值 -->
- <property name="maxActive" value="${maxActive}"/>
- <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
- <property name="maxIdle" value="${maxIdle}"/>
- <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
- <property name="minIdle" value="${minIdle}"/>
- </bean>
- </beans>
jdbc.properties
- driverClassName=org.gjt.mm.mysql.Driver
- url=jdbc:mysql://localhost:3306/royzhou?useUnicode=true&characterEncoding=UTF-8
- username=root
- password=123456
- initialSize=1
- maxActive=500
- maxIdle=2
- minIdle=1
编写我们的测试类:TestJdbcTemplate.java
- package com.royzhou.