java day30 [database connection pool, Spring JDBC: JDBC Template]

The first chapter   database connection pool

1. The concept: in fact, a container (collection), storage containers database connection.
When a good system initialization, the container is created, the container will apply for some of the connection object when the user to access the database to get a connection object from the container, after the user access to finished, the connection object will be returned to the container.

2. Benefits:
1. conserve resources
2. The user access and efficient

3. Implementation:
in DataSource javax.sql packages: 1. Standard Interface
1. Method:
* Get the connection: the getConnection ()
* return connection: Connection.close (). If the connection object Connection is to obtain from the connection pool, then call Connection.close () method, you will not close the connection. But the return connection

2. Generally, we do not realize it, there are database vendors to achieve
1. C3P0: database connection pool technology
2. Druid: database connection pool implementation technology, provided by Alibaba

4. C3P0: database connection pooling
* steps:
1. Import jar package (two) c3p0-0.9.5.2.jar mchange-Commons-Java-0.2.12.jar,
* do not forget to import database driver jar package
2. Definitions profile:
* name: c3p0.properties-config.xml or c3p0
* path: directly to files in the src directory.

3. Create a core object database connection pool object ComboPooledDataSource
4. Get connected: the getConnection
* Code:
// Create a database connection pool object.
The DataSource ComboPooledDataSource new new DS = ();
// get a connection objects 2.
Connection ds.getConnection Conn = ( );
5. the Druid: database connection pool implementation technology, provided by Ali Baba
1. step:
1. import-1.0.9.jar jar package Druid
2. Custom profile:
* is in the form of properties
* can be called any name, It can be placed in any directory
3. load the configuration file. The Properties
4. database connection pool object: to get to the plant by DruidDataSourceFactory
5. obtaining a connection: the getConnection
* Code:
// Load Profile 3.
The Properties Pro new new = the Properties ();
the InputStream DruidDemo.class.getClassLoader IS = (). the getResourceAsStream ( "druid.properties");
pro.load (IS);
.. 4 // Get object connection pool
DS = DruidDataSourceFactory.createDataSource the DataSource (Pro);
.. 5 // get connection
Connection ds.getConnection Conn = ();
2. the class definition tool
1. Define a class JDBCUtils
2. provide static code block loading configuration files, initialize the connection pool object
providing method
1. obtain connection method: obtaining a connection via a database connection pool
2. releasing resources
3. the method of obtaining the connection pool

* Code:
public class JDBCUtils {

// define a member variable the DataSource
Private the DataSource static DS;

static {
the try {
// Load profile 1
the Properties Pro new new = the Properties ();
. Pro.load (JDBCUtils.class.getClassLoader () the getResourceAsStream ( "druid.properties "));
// 2 acquires the DataSource
DS = DruidDataSourceFactory.createDataSource (Pro);
} the catch (IOException E) {
e.printStackTrace ();
} the catch (Exception E) {
e.printStackTrace ();
}
}

/ **
* Get connected
* /
public static connection the getConnection () throws SQLException {
return ds.getConnection ();
}

/ **
* releasing resources
* /
public static void close(Statement stmt,Connection conn){
/* if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if(conn != null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}*/

close(null,stmt,conn);
}

 public static void close(ResultSet rs , Statement stmt, Connection conn){

if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

IF (stmt = null!) {
the try {
stmt.close ();
} the catch (SQLException E) {
e.printStackTrace ();
}
}

IF (! Conn = null) {
the try {
conn.Close (); // return connected
} the catch (SQLException E) {
e.printStackTrace ();
}
}
}

/ **
* Get connection pool
* /

public static getDataSource the DataSource () {
return DS;
}

}

Chapter II   Spring JDBC

* Spring Framework simple package JDBC. Providing a simplified JDBCTemplate target JDBC development
* steps:
1. Import jar package
2. Create JdbcTemplate object. Dependent on the data source the DataSource
* the JdbcTemplate the JdbcTemplate new new Template = (DS);

3. Call JdbcTemplate way to do CRUD operations
* update (): execute DML statements. Add, delete, change the statement
* queryForMap (): Query Results The results are set packaged as map set, the column name as a key, the value of the value recorded as a map to put this package set
* Note: This method sets the length of the query result only. 1
* the queryForList (): the query result set of the result set list encapsulating
* Note: each package record set to a Map, then set Map set loaded to a List
* query (): the query results, the results encapsulated as a JavaBean
* query parameters: the RowMapper
* we generally use BeanPropertyRowMapper implementation class. JavaBean data to complete the automatic packaging
* new BeanPropertyRowMapper <type> (Type .class)
* queryForObject: query results, the results are wrapped object
* for the polymerization is generally a function of the query

4. Exercise:
* Requirements:
1. Review No. 1 salary data 10000
2. Add a record
delete record just added
4. query id record 1, packaged as a set of Map
5. Query all records, packaged as List
6. the query all records will be packaged as a set of objects List Emp
7. the total number of records query

* Code:

Import cn.itcast.domain.Emp;
Import cn.itcast.utils.JDBCUtils;
Import org.junit.Test;
Import org.springframework.jdbc.core.BeanPropertyRowMapper;
Import org.springframework.jdbc.core.JdbcTemplate;
org.springframework.jdbc.core.RowMapper Import;

Import a java.sql.Date;
Import the java.sql.ResultSet;
Import java.sql.SQLException;
Import java.util.List;
Import a java.util.Map;

public class JdbcTemplateDemo2 {

// Junit unit testing, allows independent execution method

// Get a JDBCTemplate objects
Private the JdbcTemplate the JdbcTemplate new new Template = (JDBCUtils.getDataSource ());
/ **
* 1. Review No. 1 salary data of 10000
* /
@Test
public void test1 () {

// 2 defined SQL
String SQL = "Update the salary SET EMP WHERE ID = 10000 = 1001";
//. 3 execute SQL.
int COUNT = template.update (SQL);
System.out.println (COUNT);
}

/ **
* 2. Add a record
* /
@Test
public void test2 () {
String SQL = "INSERT INTO emp (the above mentioned id, ename, dept_id) values (,,???)";
int COUNT = template.update (SQL, 1015, "Guo Jing" , 10);
System.out.println (COUNT);

}

/ **
* 3. Add just delete record
* /
@Test
public void Test3 () {
String SQL = "emp the Delete from the WHERE the above mentioned id =?";
Int COUNT = template.update (SQL, 1015);
System.out.println (COUNT);
}

/ **
* 4. Query id record 1001, packaged as a set of Map
* Note: the length of this method to query result set can only be. 1
* /
@Test
public void Test4 () {
String = SQL "SELECT * from EMP WHERE id = id or? = ";?
the Map <String, Object> = template.queryForMap the Map (SQL, 1001, 1002,);
System.out.println (the Map);
// {the above mentioned id = 1001, ename = Monkey King, job_id = 4, mgr = 1004 , joindate = 2000-12-17, the salary = 10000.00, Bonus = null, 20 is the dept_id =}

}

/ **
* 5. the querying all records, packaged as List
* /
@Test
public void Test5 () {
String sql = "select * from emp";
List<Map<String, Object>> list = template.queryForList(sql);

for (Map<String, Object> stringObjectMap : list) {
System.out.println(stringObjectMap);
}
}

/**
* 6. 查询所有记录,将其封装为Emp对象的List集合
*/

@Test
public void test6(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new RowMapper<Emp>() {

@Override
public Emp mapRow(ResultSet rs, int i) throws SQLException {
Emp emp = new Emp();
int id = rs.getInt("id");
String ename = rs.getString("ename");
int job_id = rs.getInt("job_id");
int mgr = rs.getInt("mgr");
Date joindate = rs.getDate("joindate");
double salary = rs.getDouble("salary");
double bonus = rs.getDouble("bonus");
int dept_id = rs.getInt("dept_id");

emp.setId(id);
emp.setEname(ename);
emp.setJob_id(job_id);
emp.setMgr(mgr);
emp.setJoindate(joindate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDept_id(dept_id);

return emp;
}
});

for (EMP Emp: List) {
System.out.println (EMP);
}
}

/ **
* 6. The query for all records will be packaged as a set of List Emp object
* /

@Test
public void test6_2 () {
String SQL = "SELECT * from EMP";
List <Emp> List = template.query (SQL, new new BeanPropertyRowMapper <Emp> (Emp.class));
for (EMP Emp: List) {
System.out.println (EMP);
}
}

/ **
* total number of records query 7.
* /

@Test
public void TEST7 () {
String = SQL "SELECT COUNT (ID) from EMP";
Long total = template.queryForObject (SQL, Long.class);
the System. Out.println (Total);
}

}

Guess you like

Origin www.cnblogs.com/xuweng/p/11245715.html