日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

jdbc template 学习总结

發布時間:2025/4/14 编程问答 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 jdbc template 学习总结 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Spring JdbcTemplate方法詳解



?JdbcTemplate主要提供以下五類方法:
execute方法:可以用于執行任何SQL語句,一般用于執行DDL語句;


update方法及batchUpdate方法:update方法用于執行新增、修改、刪除等語句;batchUpdate方法用于


執行批處理相關語句;


query方法及queryForXXX方法:用于執行查詢相關語句;


call方法:用于執行存儲過程、函數相關語句。
?
JdbcTemplate類支持的回調類:
預編譯語句及存儲過程創建回調:用于根據JdbcTemplate提供的連接創建相應的語句;


? ? ? ? ?PreparedStatementCreator:通過回調獲取JdbcTemplate提供的Connection,由用戶使用該


Conncetion創建相關的PreparedStatement;
? ? ? ? ?CallableStatementCreator:通過回調獲取JdbcTemplate提供的Connection,由用戶使用該


Conncetion創建相關的CallableStatement;
預編譯語句設值回調:用于給預編譯語句相應參數設值;


? ? ? ? ?PreparedStatementSetter:通過回調獲取JdbcTemplate提供的PreparedStatement,由用戶來


對相應的預編譯語句相應參數設值;
? ? ? ? ?BatchPreparedStatementSetter:;類似于PreparedStatementSetter,但用于批處理,需要


指定批處理大小;
自定義功能回調:提供給用戶一個擴展點,用戶可以在指定類型的擴展點執行任何數量需要的操作;


? ? ? ? ?ConnectionCallback:通過回調獲取JdbcTemplate提供的Connection,用戶可在該Connection


執行任何數量的操作;
? ? ? ? ?StatementCallback:通過回調獲取JdbcTemplate提供的Statement,用戶可以在該Statement


執行任何數量的操作;
? ? ? ? ?PreparedStatementCallback:通過回調獲取JdbcTemplate提供的PreparedStatement,用戶可


以在該PreparedStatement執行任何數量的操作;
? ? ? ? ?CallableStatementCallback:通過回調獲取JdbcTemplate提供的CallableStatement,用戶可


以在該CallableStatement執行任何數量的操作;
結果集處理回調:通過回調處理ResultSet或將ResultSet轉換為需要的形式;


? ? ? ? ?RowMapper:用于將結果集每行數據轉換為需要的類型,用戶需實現方法mapRow(ResultSet?


rs, int rowNum)來完成將每行數據轉換為相應的類型。
? ? ? ? ?RowCallbackHandler:用于處理ResultSet的每一行結果,用戶需實現方法processRow


(ResultSet rs)來完成處理,在該回調方法中無需執行rs.next(),該操作由JdbcTemplate來執行,用戶


只需按行獲取數據然后處理即可。
? ? ? ? ?ResultSetExtractor:用于結果集數據提取,用戶需實現方法extractData(ResultSet rs)來


處理結果集,用戶必須處理整個結果集;
?
接下來讓我們看下具體示例吧,在示例中不可能介紹到JdbcTemplate全部方法及回調類的使用方法,我


們只介紹代表性的,其余的使用都是類似的;
?
?1)預編譯語句及存儲過程創建回調、自定義功能回調使用:
?
java代碼:


Java代碼 ?收藏代碼


public void testPpreparedStatement1() { ?


? int count = jdbcTemplate.execute(new PreparedStatementCreator() { ?


? ? ?@Override ?


? ? ?public PreparedStatement createPreparedStatement(Connection conn) ?


? ? ? ? ?throws SQLException { ?


? ? ? ? ?return conn.prepareStatement("select count(*) from test"); ?


? ? ?}}, new PreparedStatementCallback<Integer>() { ?


? ? ?@Override ?


? ? ?public Integer doInPreparedStatement(PreparedStatement pstmt) ?


? ? ? ? ?throws SQLException, DataAccessException { ?


? ? ? ? ?pstmt.execute(); ?


? ? ? ? ?ResultSet rs = pstmt.getResultSet(); ?


? ? ? ? ?rs.next(); ?


? ? ? ? ?return rs.getInt(1); ?


? ? ? }}); ? ? ?


? ?Assert.assertEquals(0, count); ?


} ?


?
首先使用PreparedStatementCreator創建一個預編譯語句,其次由JdbcTemplate通過


PreparedStatementCallback回調傳回,由用戶決定如何執行該PreparedStatement。此處我們使用的是


execute方法。
?
2)預編譯語句設值回調使用:
?
java代碼:


Java代碼 ?收藏代碼
? ? ? ?


public void testPreparedStatement2() { ?


? String insertSql = "insert into test(name) values (?)"; ?


? int count = jdbcTemplate.update(insertSql, new PreparedStatementSetter() { ?


? ? ? @Override ?


? ? ? public void setValues(PreparedStatement pstmt) throws SQLException { ?


? ? ? ? ? pstmt.setObject(1, "name4"); ?


? }}); ?


? Assert.assertEquals(1, count); ? ? ?


? String deleteSql = "delete from test where name=?"; ?


? count = jdbcTemplate.update(deleteSql, new Object[] {"name4"}); ?


? Assert.assertEquals(1, count); ?


} ?
?
? ? ? 通過JdbcTemplate的int update(String sql, PreparedStatementSetter pss)執行預編譯sql,


其中sql參數為“insert into test(name) values (?) ”,該sql有一個占位符需要在執行前設值,


PreparedStatementSetter實現就是為了設值,使用setValues(PreparedStatement pstmt)回調方法設值


相應的占位符位置的值。JdbcTemplate也提供一種更簡單的方式“update(String sql, Object...?


args)”來實現設值,所以只要當使用該種方式不滿足需求時才應使用PreparedStatementSetter。
?
3)結果集處理回調:
?
java代碼:


Java代碼 ?收藏代碼




public void testResultSet1() { ?


? jdbcTemplate.update("insert into test(name) values('name5')"); ?


? String listSql = "select * from test"; ?


? List result = jdbcTemplate.query(listSql, new RowMapper<Map>() { ?


? ? ? @Override ?


? ? ? public Map mapRow(ResultSet rs, int rowNum) throws SQLException { ?


? ? ? ? ? Map row = new HashMap(); ?


? ? ? ? ? row.put(rs.getInt("id"), rs.getString("name")); ?


? ? ? ? ? return row; ?


? }}); ?


? Assert.assertEquals(1, result.size()); ?


? jdbcTemplate.update("delete from test where name='name5'"); ? ? ??


} ?


?
RowMapper接口提供mapRow(ResultSet rs, int rowNum)方法將結果集的每一行轉換為一個Map,當然可


以轉換為其他類,如表的對象畫形式。
?
java代碼:


Java代碼 ?收藏代碼




public void testResultSet2() { ?


? jdbcTemplate.update("insert into test(name) values('name5')"); ?


? String listSql = "select * from test"; ?


? final List result = new ArrayList(); ?


? jdbcTemplate.query(listSql, new RowCallbackHandler() { ?


? ? ? @Override ?


? ? ? public void processRow(ResultSet rs) throws SQLException { ?


? ? ? ? ? Map row = new HashMap(); ?


? ? ? ? ? row.put(rs.getInt("id"), rs.getString("name")); ?


? ? ? ? ? result.add(row); ?


? }}); ?


? Assert.assertEquals(1, result.size()); ?


? jdbcTemplate.update("delete from test where name='name5'"); ?


} ?




RowCallbackHandler接口也提供方法processRow(ResultSet rs),能將結果集的行轉換為需要的形式。
?
java代碼:


Java代碼 ?收藏代碼




public void testResultSet3() { ?


? jdbcTemplate.update("insert into test(name) values('name5')"); ?


? String listSql = "select * from test"; ?


? List result = jdbcTemplate.query(listSql, new ResultSetExtractor<List>() { ?


? ? ? @Override ?


? ? ? public List extractData(ResultSet rs) ?


? ? ?throws SQLException, DataAccessException { ?


? ? ? ? ? List result = new ArrayList(); ?


? ? ? ? ? while(rs.next()) { ?


? ? ? ? ? ? ? Map row = new HashMap(); ?


? ? ? ? ? ? ? row.put(rs.getInt("id"), rs.getString("name")); ?


? ? ? ? ? ? ? result.add(row); ?


? ? ? ? ? ?} ?


? ? ? ? ? ?return result; ?


? }}); ?


? Assert.assertEquals(0, result.size()); ?


? jdbcTemplate.update("delete from test where name='name5'"); ?


} ?


?
ResultSetExtractor使用回調方法extractData(ResultSet rs)提供給用戶整個結果集,讓用戶決定如何


處理該結果集。
?
當然JdbcTemplate提供更簡單的queryForXXX方法,來簡化開發:
?
java代碼:


Java代碼 ?收藏代碼


//1.查詢一行數據并返回int型結果 ?


jdbcTemplate.queryForInt("select count(*) from test"); ?


//2. 查詢一行數據并將該行數據轉換為Map返回 ?


jdbcTemplate.queryForMap("select * from test where name='name5'"); ?


//3.查詢一行任何類型的數據,最后一個參數指定返回結果類型 ?


jdbcTemplate.queryForObject("select count(*) from test", Integer.class); ?


//4.查詢一批數據,默認將每行數據轉換為Map ? ? ??


jdbcTemplate.queryForList("select * from test"); ?


//5.只查詢一列數據列表,列類型是String類型,列名字是name ?


jdbcTemplate.queryForList(" ?


select name from test where name=?", new Object[]{"name5"}, String.class); ?


//6.查詢一批數據,返回為SqlRowSet,類似于ResultSet,但不再綁定到連接上 ?


SqlRowSet rs = jdbcTemplate.queryForRowSet("select * from test"); ?


?
3) 存儲過程及函數回調:
首先修改JdbcTemplateTest的setUp方法,修改后如下所示:
?
?
java代碼:


Java代碼 ?收藏代碼


? ? ??


@Before ?


public void setUp() { ?


? ? String createTableSql = "create memory table test" + ?


? ? "(id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + ?


? ? "name varchar(100))"; ?


? ? jdbcTemplate.update(createTableSql); ?


? ? ? ? ?


? ? String createHsqldbFunctionSql = ?


? ? ? "CREATE FUNCTION FUNCTION_TEST(str CHAR(100)) " + ?


? ? ? "returns INT begin atomic return length(str);end"; ?


? ? jdbcTemplate.update(createHsqldbFunctionSql); ?


? ? String createHsqldbProcedureSql = ?


? ? ? "CREATE PROCEDURE PROCEDURE_TEST" + ?


? ? ? "(INOUT inOutName VARCHAR(100), OUT outId INT) " + ?


? ? ? "MODIFIES SQL DATA " + ?


? ? ? "BEGIN ATOMIC " + ?


? ? ? " ?insert into test(name) values (inOutName); " + ?


? ? ? " ?SET outId = IDENTITY(); " + ?


? ? ? " ?SET inOutName = 'Hello,' + inOutName; " + ?


? ? "END"; ?


? ? jdbcTemplate.execute(createHsqldbProcedureSql); ?


} ?


?
? ? ? ?其中CREATE FUNCTION FUNCTION_TEST用于創建自定義函數,CREATE PROCEDURE PROCEDURE_TEST


用于創建存儲過程,注意這些創建語句是數據庫相關的,本示例中的語句只適用于HSQLDB數據庫。
?
? ? ? ?其次修改JdbcTemplateTest的tearDown方法,修改后如下所示:
?
java代碼:


Java代碼 ?收藏代碼




public void tearDown() { ?


? ? jdbcTemplate.execute("DROP FUNCTION FUNCTION_TEST"); ?


? ? jdbcTemplate.execute("DROP PROCEDURE PROCEDURE_TEST"); ?


? ? String dropTableSql = "drop table test"; ?


? ? jdbcTemplate.execute(dropTableSql); ?


} ?


?
? ? ? ?其中drop語句用于刪除創建的存儲過程、自定義函數及數據庫表。
?
? ? ? ?接下來看一下hsqldb如何調用自定義函數:
?
java代碼:


Java代碼 ?收藏代碼




public void testCallableStatementCreator1() { ?


? ? final String callFunctionSql = "{call FUNCTION_TEST(?)}"; ?


? ? List<SqlParameter> params = new ArrayList<SqlParameter>(); ?


? ? params.add(new SqlParameter(Types.VARCHAR)); ?


? ? params.add(new SqlReturnResultSet("result", ?


? ? ? ?new ResultSetExtractor<Integer>() { ?


? ? ? ? ? ?@Override ?


? ? ? ? ? ?public Integer extractData(ResultSet rs) throws SQLException, ?


? ? ? ? ? ? ? ?DataAccessException { ?


? ? ? ? ? ? ? ?while(rs.next()) { ?


? ? ? ? ? ? ? ? ? ?return rs.getInt(1); ?


? ? ? ? ? ? ? ?} ?


? ? ? ? ? ? ? return 0; ?


? ? ? ?})); ?


? ? Map<String, Object> outValues = jdbcTemplate.call( ?


? ? ? ?new CallableStatementCreator() { ?


? ? ? ? ? ? @Override ?


? ? ? ? ? ? public CallableStatement createCallableStatement(Connection conn) throws?


SQLException { ?


? ? ? ? ? ? ? CallableStatement cstmt = conn.prepareCall(callFunctionSql); ?


? ? ? ? ? ? ? cstmt.setString(1, "test"); ?


? ? ? ? ? ? ? return cstmt; ?


? ? }}, params); ?


? ? Assert.assertEquals(4, outValues.get("result")); ?


} ?


? ?


?
{call FUNCTION_TEST(?)}:定義自定義函數的sql語句,注意hsqldb {?= call …}和{call …}含義是


一樣的,而比如mysql中兩種含義是不一樣的;


params:用于描述自定義函數占位符參數或命名參數類型;SqlParameter用于描述IN類型參數、


SqlOutParameter用于描述OUT類型參數、SqlInOutParameter用于描述INOUT類型參數、


SqlReturnResultSet用于描述調用存儲過程或自定義函數返回的ResultSet類型數據,其中


SqlReturnResultSet需要提供結果集處理回調用于將結果集轉換為相應的形式,hsqldb自定義函數返回


值是ResultSet類型。


CallableStatementCreator:提供Connection對象用于創建CallableStatement對象


outValues:調用call方法將返回類型為Map<String, Object>對象;


outValues.get("result"):獲取結果,即通過SqlReturnResultSet對象轉換過的數據;其中


SqlOutParameter、SqlInOutParameter、SqlReturnResultSet指定的name用于從call執行后返回的Map中


獲取相應的結果,即name是Map的鍵。


注:因為hsqldb {?= call …}和{call …}含義是一樣的,因此調用自定義函數將返回一個包含結果的


ResultSet。
?
最后讓我們示例下mysql如何調用自定義函數:
?
java代碼:


Java代碼 ?收藏代碼




public void testCallableStatementCreator2() { ?


? ? JdbcTemplate mysqlJdbcTemplate = new JdbcTemplate(getMysqlDataSource); ?


? ? //2.創建自定義函數 ?


String createFunctionSql = ?


? ? "CREATE FUNCTION FUNCTION_TEST(str VARCHAR(100)) " + ?


? ? ?"returns INT return LENGTH(str)"; ?


String dropFunctionSql = "DROP FUNCTION IF EXISTS FUNCTION_TEST"; ?


mysqlJdbcTemplate.update(dropFunctionSql); ? ? ? ??


mysqlJdbcTemplate.update(createFunctionSql); ?


//3.準備sql,mysql支持{?= call …} ?


final String callFunctionSql = "{?= call FUNCTION_TEST(?)}"; ?


//4.定義參數 ?


List<SqlParameter> params = new ArrayList<SqlParameter>(); ?


params.add(new SqlOutParameter("result", Types.INTEGER)); ?


params.add(new SqlParameter("str", Types.VARCHAR)); ?


Map<String, Object> outValues = mysqlJdbcTemplate.call( ?


new CallableStatementCreator() { ?


? ? @Override ?


? ? public CallableStatement createCallableStatement(Connection conn) throws SQLException {?


?


? ? ? CallableStatement cstmt = conn.prepareCall(callFunctionSql); ?


? ? ? cstmt.registerOutParameter(1, Types.INTEGER); ?


? ? ? cstmt.setString(2, "test"); ?


? ? ? ? return cstmt; ?


? ? }}, params); ?


? ?Assert.assertEquals(4, outValues.get("result")); ?


} ?


public DataSource getMysqlDataSource() { ?


? ? String url = "jdbc:mysql://localhost:3306/test"; ?


? ? DriverManagerDataSource dataSource = ?


? ? ? ? new DriverManagerDataSource(url, "root", ""); ? ? dataSource.setDriverClassName


("com.mysql.jdbc.Driver"); ?


? ? return dataSource; ?


} ?


? ?


getMysqlDataSource:首先啟動mysql(本書使用5.4.3版本),其次登錄mysql創建test數據庫


(“create database test;”),在進行測試前,請先下載并添加mysql-connector-java-5.1.10.jar


到classpath;


{?= call FUNCTION_TEST(?)}:可以使用{?= call …}形式調用自定義函數;


params:無需使用SqlReturnResultSet提取結果集數據,而是使用SqlOutParameter來描述自定義函數返


回值;


CallableStatementCreator:同上個例子含義一樣;


cstmt.registerOutParameter(1, Types.INTEGER):將OUT類型參數注冊為JDBC類型Types.INTEGER,此


處即返回值類型為Types.INTEGER。


outValues.get("result"):獲取結果,直接返回Integer類型,比hsqldb簡單多了吧。


?
最后看一下如何如何調用存儲過程:
?
java代碼:


Java代碼 ?收藏代碼




public void testCallableStatementCreator3() { ?


? ? final String callProcedureSql = "{call PROCEDURE_TEST(?, ?)}"; ?


? ? List<SqlParameter> params = new ArrayList<SqlParameter>(); ?


? ? params.add(new SqlInOutParameter("inOutName", Types.VARCHAR)); ?


? ? params.add(new SqlOutParameter("outId", Types.INTEGER)); ?


? ? Map<String, Object> outValues = jdbcTemplate.call( ?


? ? ? new CallableStatementCreator() { ?


? ? ? ? @Override ?


? ? ? ? public CallableStatement createCallableStatement(Connection conn) throws?


SQLException { ?


? ? ? ? ? CallableStatement cstmt = conn.prepareCall(callProcedureSql); ?


? ? ? ? ? cstmt.registerOutParameter(1, Types.VARCHAR); ?


? ? ? ? ? cstmt.registerOutParameter(2, Types.INTEGER); ?


? ? ? ? ? cstmt.setString(1, "test"); ?


? ? ? ? ? return cstmt; ?


? ? }}, params); ?


? ? Assert.assertEquals("Hello,test", outValues.get("inOutName")); ?


? ? Assert.assertEquals(0, outValues.get("outId")); ?


} ?


? ?


{call PROCEDURE_TEST(?, ?)}:定義存儲過程sql;


params:定義存儲過程參數;SqlInOutParameter描述INOUT類型參數、SqlOutParameter描述OUT類型參


數;


CallableStatementCreator:用于創建CallableStatement,并設值及注冊OUT參數類型;


outValues:通過SqlInOutParameter及SqlOutParameter參數定義的name來獲取存儲過程結果。


?
? ? ? ?JdbcTemplate類還提供了很多便利方法,在此就不一一介紹了,但這些方法是由規律可循的,第


一種就是提供回調接口讓用戶決定做什么,第二種可以認為是便利方法(如queryForXXX),用于那些比


較簡單的操作。
========

使用Spring的jdbcTemplate進一步簡化JDBC操作

http://www.cnblogs.com/Fskjb/archive/2009/11/18/1605622.html


先看applicationContext.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-2.5.xsd"><bean id="springDSN"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName"value="com.microsoft.jdbc.sqlserver.SQLServerDriver"></property><property name="url"value="jdbc:microsoft:sqlserver://localhost:1433;databasename=bbs"></property><property name="username" value="sa"></property><property name="password" value="sa"></property></bean><bean id="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate" abstract="false"lazy-init="false" autowire="default" dependency-check="default"><property name="dataSource"><ref bean="springDSN" /></property></bean> </beans>

在看SpringUtil類?
package com.r.dao;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public final class SpringUtil {private static ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");public static Object getBean(String beanName){return ctx.getBean(beanName);} }
?
最后看DAO:
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map;import org.springframework.jdbc.core.JdbcTemplate;import com.r.vo.Book;public class BookDao {private JdbcTemplate jdbcT = (JdbcTemplate) SpringUtil.getBean("jdbcTemplate");public List findALL() {String sql = "select * from BookInfo";return jdbcT.queryForList(sql); }public List<Book> findALLBooks() {List<Book> books = new ArrayList<Book>();;String sql = "select * from BookInfo";List list = jdbcT.queryForList(sql); Iterator iterator = list.iterator();Book book = null;while (iterator.hasNext()) {Map map4book = (Map) iterator.next();book = new Book();book.setBid((Integer) map4book.get("bid"));book.setBookName((String)map4book.get("bookName"));book.setBookType((String)map4book.get("bookType")); book.setBookPic(((BigDecimal)map4book.get("bookPic")).doubleValue() ); book.setCount((Integer) map4book.get("count"));books.add(book);}return books;} public int delete(int bid){String sql = "delete from BookInfo where bid =?";return jdbcT.update(sql, new Object[]{bid});} public static void main(String[] args) { List<Book> books = new BookDao().findALLBooks();;for(Book book:books){System.out.println(book.getBid()+","+book.getBookName()+","+book.getBookType());}} }
?
細心你,會發現JdbcTemplate的實例中有一系列的方法如:queryForXXX,update,delete大大簡化了JDBC


操作。


當然,還可以再進一步的優化一下,就是通過依賴注入,直接把jdbcTemplate注入到dao類的jdbcT字段。


先看新的applicationContext.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-2.5.xsd">


? ? <bean id="springDSN"
? ? ? ? class="org.springframework.jdbc.datasource.DriverManagerDataSource">
? ? ? ? <property name="driverClassName"
? ? ? ? ? ? value="com.microsoft.jdbc.sqlserver.SQLServerDriver">
? ? ? ? </property>
? ? ? ? <property name="url"
? ? ? ? ? ? value="jdbc:microsoft:sqlserver://localhost:1433;databasename=bbs">
? ? ? ? </property>
? ? ? ? <property name="username" value="sa"></property>
? ? ? ? <property name="password" value="sa"></property>
? ? </bean>


? ? <bean id="jdbcTemplate"
? ? ? ? class="org.springframework.jdbc.core.JdbcTemplate" abstract="false"
? ? ? ? lazy-init="false" autowire="default" dependency-check="default">
? ? ? ? <property name="dataSource">
? ? ? ? ? ? <ref bean="springDSN" />
? ? ? ? </property>
? ? </bean>


? ? <bean id="bookDao" class="com.yy.struts.dao.BookDao">
? ? ? ?<property name="jdbcT">
? ? ? ? ? <ref bean="jdbcTemplate" />
? ? ? ?</property>
? ? </bean>
</beans>
復制代碼
?那么新的DAO類:


復制代碼
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import org.springframework.jdbc.core.JdbcTemplate;


import com.r.vo.Book;


public class BookDao {


? ? private JdbcTemplate jdbcT;


? ? public List findALL() {
? ? ? ? String sql = "select * from BookInfo";
? ? ? ? return jdbcT.queryForList(sql); ? ? ? ?
? ? }


? ? public List<Book> findALLBooks() {
? ? ? ? List<Book> books = new ArrayList<Book>();;
? ? ? ? String sql = "select * from BookInfo";
? ? ? ? List list = jdbcT.queryForList(sql);?
? ? ? ? Iterator iterator = list.iterator();
? ? ? ? Book book = null;
? ? ? ? while (iterator.hasNext()) {
? ? ? ? ? ? Map map4book = (Map) iterator.next();
? ? ? ? ? ? book = new Book();
? ? ? ? ? ? book.setBid((Integer) map4book.get("bid"));
? ? ? ? ? ? book.setBookName((String)map4book.get("bookName"));
? ? ? ? ? ? book.setBookType((String)map4book.get("bookType")); ? ? ? ?
? ? ? ? ? ? book.setBookPic(((BigDecimal)map4book.get("bookPic")).doubleValue() ); ? ? ? ? ?


??
? ? ? ? ? ? book.setCount((Integer) map4book.get("count"));
? ? ? ? ? ? books.add(book);
? ? ? ? }
? ? ? ? return books;
? ? } ? ?
? ? public int delete(int bid){
? ? ? ? String sql = "delete from BookInfo where bid =?";
? ? ? ? return jdbcT.update(sql, new Object[]{bid});
? ? } ? ??
? ? public static void main(String[] args) { ? ? ? ?
? ? ? ? List<Book> books = new BookDao().findALLBooks();;
? ? ? ? for(Book book:books){
? ? ? ? ? ? System.out.println(book.getBid()+","+book.getBookName()+","+book.getBookType


());
? ? ? ? }
? ? }
}
復制代碼
?


?通過依賴注入,對象之間的關系由SPRING來維護,這樣能降低類與類的耦合度
========

JdbcTemplate學習筆記



1、使用JdbcTemplate的execute()方法執行SQL語句


Java 代碼
? ??
jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");
? ??
jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))"); ?
2、如果是UPDATE或INSERT,可以用update()方法。


Java 代碼
? ??
jdbcTemplate.update("INSERT INTO USER VALUES('" ?
? ??
+ user.getId() + "', '" ?
? ??
+ user.getName() + "', '" ?
? ??
+ user.getSex() + "', '" ?
? ??
+ user.getAge() + "')"); ?
? ??
jdbcTemplate.update("INSERT INTO USER VALUES('" ?
? ??
+ user.getId() + "', '" ?
? ??
+ user.getName() + "', '" ?
? ??
+ user.getSex() + "', '" ?
? ??
+ user.getAge() + "')"); ?
3、帶參數的更新


Java代碼
? ??
jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?", new Object[] {name, id});?


? ?
? ??
jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?", new Object[] {name, id});?


?
Java代碼
? ??
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", new Object[] {user.getId(),?


user.getName(), user.getSex(), user.getAge()}); ? ?
? ??
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", new Object[] {user.getId(),?


user.getName(), user.getSex(), user.getAge()}); ?
4、使用JdbcTemplate進行查詢時,使用queryForXXX()等方法


Java代碼
? ??
int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER"); ? ?
? ??
int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER"); ?
Java代碼
? ??
String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id =?


?", new Object[] {id}, java.lang.String.class); ? ?
? ??
String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id =?


?", new Object[] {id}, java.lang.String.class); ?
Java代碼
? ??
List rows = jdbcTemplate.queryForList("SELECT * FROM USER"); ? ?
? ??
List rows = jdbcTemplate.queryForList("SELECT * FROM USER"); ?
Java代碼
? ??
List rows = jdbcTemplate.queryForList("SELECT * FROM USER"); ?
? ??
Iterator it = rows.iterator(); ?
? ??
while(it.hasNext()) { ?
? ??
Map userMap = (Map) it.next(); ?
? ??
System.out.print(userMap.get("user_id") + "\t"); ?
? ??
System.out.print(userMap.get("name") + "\t"); ?
? ??
System.out.print(userMap.get("sex") + "\t"); ?
? ??
System.out.println(userMap.get("age") + "\t"); ?
? ??
} ?
? ??
??
? ??
List rows = jdbcTemplate.queryForList("SELECT * FROM USER"); ?
? ??
??
? ??
Iterator it = rows.iterator(); ?
? ??
while(it.hasNext()) { ?
? ??
Map userMap = (Map) it.next(); ?
? ??
System.out.print(userMap.get("user_id") + "\t"); ?
? ??
System.out.print(userMap.get("name") + "\t"); ?
? ??
System.out.print(userMap.get("sex") + "\t"); ?
? ??
System.out.println(userMap.get("age") + "\t");?
? ??
? ??
} ?
JdbcTemplate將我們使用的JDBC的流程封裝起來,包括了異常的捕捉、SQL的執行、查詢結果的轉換等等


。spring大量使用Template Method模式來封裝固定流程的動作,XXXTemplate等類別都是基于這種方式


的實現。


除了大量使用Template Method來封裝一些底層的操作細節,spring也大量使用callback方式類回調相關


類別的方法以提供JDBC相關類別的功能,使傳統的JDBC的使用者也能清楚了解spring所提供的相關封裝


類別方法的使用。


JDBC的PreparedStatement


Java代碼
? ??
final String id = user.getId(); ? ?
? ??
final String name = user.getName(); ? ?
? ??
final String sex = user.getSex() + ""; ? ?
? ??
final int age = user.getAge(); ?
? ??
??
? ??
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", ?
? ??
??
? ??
new PreparedStatementSetter() { ? ?
? ??
public void setValues(PreparedStatement ps) throws SQLException { ? ?
? ??
ps.setString(1, id); ?
? ??
ps.setString(2, name); ?
? ??
ps.setString(3, sex); ?
? ??
ps.setInt(4, age); ?
? ??
} ?
? ??
}); ?
? ??
??
? ??
final String id = user.getId(); ?
? ??
final String name = user.getName(); ?
? ??
final String sex = user.getSex() + ""; ?
? ??
final int age = user.getAge(); ?
? ??
? ??
? ??
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", ?
? ??
? ??
? ??
new PreparedStatementSetter() { ? ? ?
? ??
public void setValues(PreparedStatement ps) throws SQLException { ? ?
? ??
ps.setString(1, id); ? ?
? ??
ps.setString(2, name); ? ? ?
? ??
ps.setString(3, sex); ? ?
? ??
ps.setInt(4, age); ? ? ?
? ??
} ? ?
? ??
}); ? ? ? ?
Java代碼
? ??
final User user = new User(); ? ? ?
? ??
jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?", ? ?
? ??
new Object[] {id}, ? ?
? ??
new RowCallbackHandler() { ? ?
? ??
public void processRow(ResultSet rs) throws SQLException { ? ?
? ??
user.setId(rs.getString("user_id")); ?
? ??
user.setName(rs.getString("name")); ?
? ??
user.setSex(rs.getString("sex").charAt(0)); ? ?
? ??
user.setAge(rs.getInt("age")); ? ?
? ??
} ?
? ??
}); ?
? ??
??
? ??
final User user = new User(); ?
? ??
? ??
? ??
jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?", ? ?
? ??
new Object[] {id}, ? ? ?
? ??
new RowCallbackHandler() { ?
? ??
??
? ??
??
? ??
public void processRow(ResultSet rs) throws SQLException { ? ?
? ??
user.setId(rs.getString("user_id")); ? ?
? ??
user.setName(rs.getString("name")); ? ?
? ??
user.setSex(rs.getString("sex").charAt(0)); ? ?
? ??
user.setAge(rs.getInt("age")); ? ?
? ??
} ? ?
? ??
}); ?
Java代碼
? ??
class UserRowMapper implements RowMapper { ?
? ??
??
? ??
public Object mapRow(ResultSet rs, int index) throws SQLException { ?
? ??
??
? ??
User user = new User(); ?
? ??
user.setId(rs.getString("user_id")); ? ? ?
? ??
user.setName(rs.getString("name")); ? ?
? ??
user.setSex(rs.getString("sex").charAt(0)); ? ? ?
? ??
user.setAge(rs.getInt("age")); ? ? ?
? ??
return user; ? ? ? ??
? ??
} ? ? ? ??
? ??
} ?
? ??
? ??
? ??
public List findAllByRowMapperResultReader() { ? ? ?
? ??
??
? ??
String sql = "SELECT * FROM USER"; ?
? ??
??
? ??
return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper())); ?
? ??
??
? ??
} ?
? ??
??
? ??
class UserRowMapper implements RowMapper { ?
? ??
??
? ??
public Object mapRow(ResultSet rs, int index) throws SQLException { ?
? ??
User user = new User(); ? ?
? ??
user.setId(rs.getString("user_id")); ? ?
? ??
user.setName(rs.getString("name")); ? ?
? ??
user.setSex(rs.getString("sex").charAt(0)); ? ?
? ??
user.setAge(rs.getInt("age")); ? ?
? ??
return user; ? ?
? ??
} ? ?
? ??
} ?
? ??
??
? ??
public List findAllByRowMapperResultReader() { ? ? ?
? ??
String sql = "SELECT * FROM USER"; ? ?
? ??
return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper())); ?
? ??
} ?
在getUser(id)里面使用UserRowMapper


Java代碼
? ??
public User getUser(final String id) throws DataAccessException { ? ?
? ??
String sql = "SELECT * FROM USER WHERE user_id=?"; ? ?
? ??
final Object[] params = new Object[] { id }; ? ?
? ??
List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper


())); ? ? ?
? ??
return (User) list.get(0); ? ?
? ??
}
? ??
??
? ??
public User getUser(final String id) throws DataAccessException { ?
? ??
String sql = "SELECT * FROM USER WHERE user_id=?"; ? ? ?
? ??
final Object[] params = new Object[] { id }; ? ? ?
? ??
List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper


())); ? ? ?
? ??
return (User) list.get(0); ? ? ?
? ??
}
網上收集


org.springframework.jdbc.core.PreparedStatementCreator 返回預編譯SQL 不能于Object[]一起用


Java代碼
? ??
public PreparedStatement createPreparedStatement(Connection con) throws SQLException { ? ?
? ??
return con.prepareStatement(sql); ? ?
? ??
} ?
? ??
??
? ??
public PreparedStatement createPreparedStatement(Connection con) throws SQLException { ? ?
? ??
return con.prepareStatement(sql); ? ?
? ??
} ?
1.增刪改


org.springframework.jdbc.core.JdbcTemplate 類(必須指定數據源dataSource)


Java代碼
? ??
template.update("insert into web_person values(?,?,?)",Object[]); ? ?
? ??
template.update("insert into web_person values(?,?,?)",Object[]); ?
? ??



Java代碼
? ??
template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){ //匿


名內部類 只能訪問外部最終局部變量 ? ?
? ??
public void setValues(PreparedStatement ps) throws SQLException { ? ?
? ??
ps.setInt(index++,3); ? ?
? ??
}); ?
? ??
??
? ??
template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){ //匿


名內部類 只能訪問外部最終局部變量 ?
? ??
??
? ??
public void setValues(PreparedStatement ps) throws SQLException { ? ?
? ??
ps.setInt(index++,3); ? ?
? ??
}); ?
? ??
??
? ??
org.springframework.jdbc.core.PreparedStatementSetter //接口 處理預編譯SQL ? ? ? ?
? ??
public void setValues(PreparedStatement ps) throws SQLException { ? ?
? ??
ps.setInt(index++,3); ? ?
? ??
} ?
? ??
??
? ??
public void setValues(PreparedStatement ps) throws SQLException { ? ?
? ??
ps.setInt(index++,3); ? ?
? ??
} ?
2.查詢JdbcTemplate.query(String,[Object


[]/PreparedStatementSetter],RowMapper/RowCallbackHandler)


org.springframework.jdbc.core.RowMapper 記錄映射接口 處理結果集


Java代碼
? ??
public Object mapRow(ResultSet rs, int arg1) throws SQLException { //int表當前行數 ? ?
? ??
person.setId(rs.getInt("id")); ? ?
? ??
} ? ?
? ??
List template.query("select * from web_person where id=?",Object[],RowMapper); ? ?
? ??
public Object mapRow(ResultSet rs, int arg1) throws SQLException { //int表當前行數 ? ?
? ??
person.setId(rs.getInt("id")); ? ?
? ??
} ? ?
? ??
List template.query("select * from web_person where id=?",Object[],RowMapper); ?
org.springframework.jdbc.core.RowCallbackHandler 記錄回調管理器接口 處理結果集


Java代碼
? ??
template.query("select * from web_person where id=?",Object[],new RowCallbackHandler(){ ? ?
? ??
public void processRow(ResultSet rs) throws SQLException { ? ?
? ??
person.setId(rs.getInt("id")); ? ?
? ??
}); ?
======== 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的jdbc template 学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。