JDBC (java database connection technology) and DBCP (database connection pool) combined use

1. Configuration file

First of all, we need to create and create the db.properties configuration file (the properties file can read the file content through the Properties object, and then read the content waiting for the back according to the content before the equal sign, which is similar to the key and value of the map), the content of the file:

oracle writing:

driver=oracle.jdbc.driver.OracleDriver

url=oracle:jdbc:thin:@127.0.0.1 (native database):1521:xe (10g is xe11g is orcl)

user=scott (the database already has an account)

pwd=corresponding account password

mysql writing:

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://127.0.0.1(native database):3306:/test(name of corresponding database)

user=root

pwd=password set when installing the database

2. DBUtil tool class

public class DBUtil{
	private static String driver;
	private static String url;
	private static String user;
	private static String pwd;
	//create connection pool object
	private static BasicDataSource bds = new BasicDataSource();
	/*
	 * Static code blocks, loaded ahead of time when the class is loaded
	 */
	static{
		try {
			FileReader fr = new FileReader("db.properties");//Read the configuration file
			Properties prop = new Properties();//Create a Properties object to read the corresponding content in the file
			prop.load(fr);//Load the file
			/* read related properties */
			driver = prop.getProperty("driver");
			url = prop.getProperty("url");
			user = prop.getProperty("user");
			pwd = prop.getProperty("pwd");
			
			//Set parameters for connection pool
			bds.setDriverClassName(driver);
			bds.setUrl(url);
			bds.setUsername(user);
			bds.setPassword(pwd);
			
			//Initialize the number of connections
			bds.setInitialSize(5);
			//Maximum number of actives, how many time points can be active at the same time
			bds.setMaxActive(8);
			//Maximum number of idle connections
			bds.setMaxIdle(4);
			//Minimum number of idle connections, the closer the two numbers are, the smaller the overhead
			bds.setMinIdle(4);
			//Maximum waiting time in milliseconds
			bds.setMaxWait(30);
			
			
			/*
			 * Using JDBC Step 1: Load the driver
			 */
			Class.forName(driver);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace ();
		}
	}
	/**
	 * Create a connection method to create a database connection call method
	 * @return Connection database connection object
	 */
	public static Connection getConn(){
		Connection conn = null;
		try {
			conn = bds.getConnection();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return conn;
	}
	/**
	 * Database connection close method
	 * @param conn database connection object
	 */
	public static void closeConn(Connection conn){
		try {
			if(conn!=null){
				//Disconnect and return to the connection pool
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace ();
		}
	}
}

3. Use of DBUtil class (eq is the oracle database insertion method)

	public void addEmp(Emp emp) {
		// TODO Auto-generated method stub
		Connection conn = null;
		try {
			//1. Create connection and load driver
			conn = DBUtil2.getConn();
			//Set the processing transaction to manual
			conn.setAutoCommit(false);
			//2. The sql statement to be executed
			String sql = "insert into emp values(?,?,?,?,?,?,?,?)";
			//3. Create a PreparedStatement statement object
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt (1, emp.getEmpno ());
			ps.setString(2, emp.getEname());
			ps.setString(3, emp.getJob());
			ps.setInt(4, emp.getMgr());
			ps.setDate(5, emp.getHiredate());
			ps.setDouble(6, emp.getSal());
			ps.setDouble(7, emp.getComm());
			ps.setInt(8, emp.getDeptno());
			//4. Execute the sql statement object, the return value is how many rows of data are affected
			ps.executeUpdate();
			conn.commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace ();
			try {
				conn.rollback();				
			} catch (Exception e2) {
				// TODO: handle exception
				e.printStackTrace ();
			}
		}finally{
			/*
			 * 5. The connection should be closed after use
			 */
			DBUtil2.closeConn(conn);
		}
	}

Explanation: Why using PreparedStatement does not use Statement as the object of sql statement execution?

1.PerparedStatement executes dynamic sql statements, use? As a placeholder, use setDataType(1, x) as the assignment method, and Statement executes a static sql statement

2. Statement has sql injection vulnerability

3. PreparedStatement executes multiple sql statements only need to compile once each time, Statement executes multiple sql statements need to compile multiple times

4. Singleton pattern: object implementation that implements persistence layer code

There are three necessary conditions to use the singleton pattern:

1. The property is static private

2. The class to use the singleton pattern cannot be instantiated, that is, the constructor is privatized

3. There is a static method to assign values ​​to properties

Description: Two modes of the singleton mode:

        a. (lazy man mode): understandably unwilling to do it, the attribute is not assigned at the beginning, the method needs to be assigned, and the call

	//1. Private property
	private static EmpDao dao = null;

	//2. Constructor privatization
	private DaoFactory(){}
	
	//3. Object
	public static EmpDao getInstance(){
		if(dao == null){
			dao = new EmpDaoMysqlImpl();
			//dao = new EmpDaoImpl();
		}
		return dao;
	}

        b. (Hungry man mode): It is understandable that you want to do it urgently. At the beginning, the attribute has a value, and there is no need to assign a value to the method. The method just calls

	//1. Private property
	private static EmpDao dao = new EmpDaoMysqlImpl();

	//2. Constructor privatization
	private DaoFactory(){}
	
	//3. Object
	public static EmpDao getInstance(){
		return dao;
	}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325502046&siteId=291194637