一.不使用xml配置文件的形式
(1)使用DriverManagerDataSource創建一個數據源
(2)創建一個jdbbcTemplate對象
(3)使用該對象執行sql語句
@Test
public void handle2(){
/**
*數據源
*/
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8");
dataSource.setUsername("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
String sql="create table tb_user(user_id int primary key,username varchar(60),password varchar(60))";
jdbcTemplate.execute(sql);
}
二.使用xml配置文件
(1)配置數據源
(2)配置jdbcTemplateBean
xml配置文件:
<!-- 引入屬性文件-->
<context:property-placeholder location="classpath:db.properties" file-encoding="utf-8"/>
<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
/>
<!-- 聲明jdbcTemplateBean -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"
/>
(3)測試
@Test
public void handle3(){
String sql="insert into tb_user(user_id,username,password)values(1,'moweng','123456')";
jdbcTemplate.execute(sql);
}
三.jdbcTemplate的update
(1)int update
爲不帶佔位符的sql語句提供便利
(2)int update(sql,Object[] object)
(3)int update(sql,Object[] object,int[] argTypes)
(4)int update(sql,PrepareStatementSetters pass)
(5)int update(preparedStatementCreators psc);
@Test
public void handl4(){
String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(sql,new Object[]{"23456","moweng"});
}
@Test
public void handl5(){
String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(sql,new Object[]{"234561","moweng"},new int[]{Types.VARBINARY,Types.VARBINARY});
}
@Test
public void handl6(){
String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(sql,new PreparedStatementSetter(){
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1,"23989");
ps.setString(2, "moweng");
}
});
}
@Test
public void handl7(){
final String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,"df9");
ps.setString(2, "moweng");
return ps;
}
});
}
四.spring提供了一個可以返回新增記錄對應主鍵值的方法
int update(PreparedStatementCreator psc,KeyHolder generatedKeyHolder)
org.springwork.jdbc.support.KeyHolder是一個回調接口,spring使用它保存新增記錄對應的主鍵。
Number getKey() throws InvalidDataAccessApiUsageException
當插入一行數據,主鍵不是複合鍵而是字符類型
Map<String,Object>getKeys()throws InvalidDataAccessApiUsageException
如果是複合鍵,則列和列值構成了Map中的一個Entry,如果是多個主鍵,則報錯
List<Map<String,Object>>getKeys()throws InvalidDataAccessApiUsageException
如果返回了多個主鍵,即prepareStatement新增了多條記錄,則每個主鍵對應一個Map,多個Map構成了一個list
@Test
public void handl8(){
final String sql="insert into tb_user(username,password)values(?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(2,"df90");
ps.setString(1, "yaping");
return ps;
}
},keyHolder);
System.out.println(keyHolder.getKey().intValue());
}
五.jdbcTemplate批量操作數據的方法
(1)public int[] batchUpdate(String[] sql)
多條sql語句組成一個數組(這些sql語句不帶參數),該方法以批量方式執行這些sql語句spring在內部使用jdbc提供的批量更新API完成操作,如果底層不支持批量操作,spring將採用逐條更新的方式模擬批量更新
(2)public int[] batchUpdate(String sql,BatchPreparedStatementSetter ps)
對於同一結構帶參sql語句多次進行數據更新操作,通過batchPreparedStatementSetter 回調接口進行批量參數綁定工作
int getBatchSize();指定本批次的大小
void setValues(preparestatement ps,int index)
@Test
public void handle9(){
String sql = "insert into tb_user(username,password)values(?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int index) throws SQLException {
ps.setString(1,"moweng"+index);
ps.setString(2,"1234");
}
@Override
public int getBatchSize() {
return 5;
}
});
}
六.查詢語句
RowcallbackHandler
@Test
public void handle11(){
String sql = "select * from tb_user where username=?";
jdbcTemplate.query(sql,new Object[]{"moweng"}, new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
System.out.println(rs.getString("username")+"=========="+rs.getString("password"));
}
});
}
七.調用存儲過程
jdbcTemplate提供了兩個調用存儲過程的接口方法
(1)<T> execute(String callString,CallableStatementCallBack<T> action)
callstring 指定調用存儲過程的sql語句;第二個參數CallableStatementCallback<T>是一個回調接口,該接口只有一個方法,
T doInCallableStatement(CallableStatement cs),用戶可以在這個方法這進行輸入參數綁定,輸出參數註冊以及返回數據的處理
(2)<T> execute(CallableStatementCreator csc,CallableStatementCallback<T> action)
CallableStatementCreator 負責創建callablestatement實例,綁定參數,註冊輸出參數,callableStatementcallback負責處理存儲過程的返回結果
@Test
public void handle12(){
String sql="{call getCount(?,?)}";
Integer num = jdbcTemplate.execute(sql, new CallableStatementCallback() {
@Override
public Object doInCallableStatement(CallableStatement cs)
throws SQLException, DataAccessException {
cs.setInt(1, 1);
cs.registerOutParameter(2, Types.INTEGER);
cs.execute();
return cs.getInt(2);
}
});
System.out.println(num+"====");
}
@Test
public void handle13(){
String sql="{call getCount(?,?)}";
CallableStatementCreatorFactory fc = new CallableStatementCreatorFactory(sql);
fc.addParameter(new SqlParameter("in_userid",Types.INTEGER));
fc.addParameter(new SqlOutParameter("out_num",Types.INTEGER));
Map<String, Object> maps = new HashMap<String, Object>();
maps.put("in_userid", 1);
CallableStatementCreator cs = fc.newCallableStatementCreator(maps);
int num=jdbcTemplate.execute(cs,new CallableStatementCallback<Integer>() {
@Override
public Integer doInCallableStatement(CallableStatement css)
throws SQLException, DataAccessException {
css.execute();
return css.getInt(2);
}
});
System.out.println("==============="+num);
}