Learn Spring JDBC

zhaozj2021-02-16  146

First go to http://sourceforge.net/project/showfiles.php?group_id=73357 to download the Spring development package. Put Spring.jar, Log4j.jar, etc., is OK.

spring jdbc framework composed of four packages: org.springframework.jdbc.core; org.springframework.jdbc.datasource; org.springframework.jdbc.object; org.springframework.jdbc.supportspring jdbc is the exception in org.springframework.dao Implement 1. Org.springframework.jdbc.core.jdbcTemplate is a Spring core class, which gets Connection from DataSource and turn off the connection. It completes SQL's Insert / Update / Delete / Query / Store Proc below is some examples of it: import org.springframework.jdbc.core.jdbcTemplate; public void do (DataSource DS) {JDBCTemplate JT = New JDBCTemplate (DS); JT "CREATE TABLE MYTABLE (" Create Table MyTable ("Create Table MyTable (" CREGER, NAME VARCHAR (100)) "); JT.UPDATE (" Update Table Set Name =? Where id =? ", new object [] {name, new integer (id)} ); Int count = jt.queryforint ("Select Count (*) from table"); string str = (String) jt.queryforObject ("Select Name from Table Where Id = 1", String.class); List List = List) Jt.QueryforList ("SELECT * from Table");

2. Query org.springframework.jdbc.object.MappingSqlQueryimport org.springframework.jdbc.object.MappingSqlQuery; public class mappingSqlQuery {public Product getProduct () {CustomerMappingSqlQuery cm = new CustomerMappingSqlQuery (ds); Object [] parms = new Object [1]; parms [0] = new Integer (1); List list = cm.execute (parms);} private class CustomerMappingSqlQuery extends MappingSqlQuery {public CustomerMappingSqlQuery (DataSource ds) {super (ds, "select id, name from table where id =? "); super.declareParameter (new SqlParameter (" id ", Types.INTEGER)); compile ();} public Object mapRow (ResultSet rs, int rowNumber) throws SQLException {Product product = new Product (); product.setId ( Rs.Getint ("ID")); Product.SetDescription (rs.getstring ("name")); Return Product;}}} 3. Modify Org.SpringFramework.jdbc.Object.sqlupdate public int doupdate (DataSource DS) {SQLUPDATE SU = New SQLUPDATE (); Su.SetDataSource (DS); Su.setSql ("Update Table Set Name =? Where id =?") Su.DeclareParameter (New SqlParameter ("Name", Types.varchar); Su.compile ();

Object [] params = new object [2]; params [0] = "name"; params [1] = new integer (1); return su.update (params);} 4. Simple ORG.SPRINGFRAMEWORK.JDBC.Object.sqlfunction public int count () {SQLFunction sf = new SQLFunction (DS, "SELECT Count (*) from myTable"); sf.compile (); return sf.run ()

转载请注明原文地址:https://www.9cbs.com/read-7922.html

New Post(0)