データベース接続プールとDBUtilsツールパッケージのシミュレーション


Oracleの3つのプライマリ・ユーザー:scottパスワード:tiger一般管理者:systemパスワード:managerスーパー管理者:sysパスワード:change_on
1.clobテキストデータMysql ORACLEの文字データを挿入して読み取る、最大4 G 2に達することができる.Blobバイナリデータの挿入と読み取り、MySqlのBlobは16 KBのデータを格納し、OracleのBlob長とは異なるバイナリデータを格納し、最大4 G 3に達することができる.本当にバイナリデータを格納するにはトランザクションを使用し、カーソルはまずemptyを挿入します.blob()関数、再クエリー、4.2種類のバッチaddBatch()|addBatch(sql)、forループを挿入または読み取ります.データが大きすぎる場合、仮想機会メモリがオーバーフローした場合、1000個の場合、セグメント化されたバッチでexecuteBatch()を実行します.5.データベースが自動的に生成するプライマリ・キーPreparedStatementを取得する.getGeneratedKeys();//stオブジェクトパッケージのsqlのプライマリ・キーを返します.MySQLで他のデータベースであればconn.preparedStatement(sql,Statement.RETURN_GENERATED_KEYS)を実行する定数値を加算して、ORACLEでも6.ストアド・プロシージャCallableStatementc=conn.preparedCall("{call demeSp(?)});返却を取得する際にデータベースに返却値のタイプc.registerOutParameter(2,Types.VARCHAR 2);7.トランザクション@Connectionオブジェクトがオートコミットモードにある場合、各文を実行した後に変更が自動的にコミットされるため、conn.settAutoCommit(false)が必要です.終わったらまたcommit();異常がある場合catch()で手動(自動)conn.rollback();@SavaPointロールバックポイント@トランザクションのプロパティ(ACID)アトミック(Atomicity):成功、失敗の一貫性(Consistency):前後データの一貫性、独立性(Isolation):同時トランザクション、操作データの分離、持続性(Durability):commitのみ、隔離されていない可能性のあるものを保存する必要があります:汚い読み:1つの物事が他の人に提出されていないデータ例:売買は繰り返して読むことができません:1つの事務が提出されたデータ例を読みました:2人がデータレポートを読んで虚読(幻読み)します:1つの物事内で他の人が挿入したデータ例を読みました:幻文の現在のデータベース接続レベル:set transaction isolation level read uncommitted;最低レベルset transaction isolation level read committedを設定します.読取りレベル(会計検査用)set transaction isolation level repeatable committedを設定します.繰り返しコミットでき、set transaction isolation level Serializableを幻読できない.//単一スレッドレベル、他のユーザーがアクセスできない(デッドロックする)start starnsaction;トランザクション・レベル設定serializableをオンにすると、共有ロックが発生します.どんなレベルでもupdateをすると排他的にロックされます.共有ロック解決策---楽観ロック:バージョン番号を追加して更新損失を解決し、update後にversionフィールドを追加します.プログラムが同時である場合、ロールバックはパフォーマンスの低下をもたらします.排他ロック---悲観ロック:select..for update;1つのアカウントを待つ必要があります:システムは更新が多いのか、それともクエリーが多いのか、クエリーは楽観的なロックが多いのか、更新は悲観的なロックが多いのはインデックス列であれば、行をロックし、他のユーザーは他の行を操作することができます.(行レベルロック)そうでない場合は、テーブル全体をロックします.[構成をインストールするとき]innodbエンジンを設定してこそ、トランザクションと行レベルのロックをサポートします(トランザクションが多いことを考慮します)myisamの場合、表レベルのロック(クエリーシステムでこれを使用します)Oracleのみが異なります.Oracleはデータのロックギャップロックに対してです:where id>2 for update==================================================================16実際の開発では、開発を強化クラスを継承し、実装を強化する方法を上書きします.2.包装decorateモード、インタフェースを実現し、強化方法3動的代理技術を用いて包装設計モード*1を構築する.エンハンスメントされたクラスと同じインタフェースを実装クラス*2を書く.クラスに変数を定義し、拡張オブジェクト*3を記憶します.クラス内の構築方法を定義し、拡張オブジェクト*4を受信する.強化したいメソッドを書き換える*5.拡張したくないメソッドの場合、拡張対象のメソッドデータベース接続プールをメソッド内で直接呼び出すには、@1の3種類があります.DBCP開発ライブラリ:commons-dbcp.jar,commons-pool.jddbc 1.new BasicDataSourceFactory()を取得します.2.DataSource ds = factory.createDataSource(properties);プール接続conn=dsを構築する.getConnection(); @2.C 3 P 0開発ライブラリc 3 p 0.jar ,mchange-commons-0.2 1.ComboPooledDataSource ds = new ();/*2.Dds.setUrl//ドライバを設定し、接続名パスワードを設定し、プールサイズを初期化します.他の値はdsをデフォルトにします.getConnection();*/2.プロファイルc 3 p 0-configを使用することもできる.xml,//コンフィギュレーションファイルで構成されているデータベースを指定し、デフォルトコンフィギュレーションCommoPooledDataSource ds=new("mysql");3.tomcatでの接続プールの原理:DAOはjdbUtilsを介してJIDIコンテナから取得するDataSource:app/datasourceプロファイルもMETA-INFディレクトリの下にcontextを書くことができる.xml注意:tomcatでこのxmlが自動的に生成されます.手順1.jarパッケージをtomcatのlibパッケージのように2.tomacatのドキュメントにjndiのプロファイル3が見つかりました.プロジェクトMETA-INFでcontextを加える.xmlプロファイル4.以下でConnectionオブジェクトprivate static DataSource ds=null;static{try{Context initCtx=new InitialContext();Context envCtx=(Context)initCtx.lookup("java:comp/env");ds=(DataSource)envCtx.lookup("jdbc/EmployeeDB"); } catch (Exception e) { throw new RuntimeException(e); } }
 
 
 
 
 
 
 
 
         
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

public class JdbcPool implements DataSource {

	private static LinkedList<Connection> list = new LinkedList<Connection>();
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
			for(int i=0;i<20;i++){
				Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day16", "root", "root");
				System.out.println(conn);
				list.add(conn);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/*
	 1.     ,        ()
	 2.       
	 3.     
	 */
	
	/*
	class MyConnection extends mysqlConnection{
		public void close(){
			
		}
	}
	
	/*
	 * 1.                
	 * 2.         ,       
	 * 3.           ,       
	 * 4.        
	 * 5.         ,                  
	 */
	/*
	class MyConnection implements Connection{
		private Connection conn;
		public MyConnection(Connection conn){
			this.conn = conn;
		}
		public void close() throws SQLException {
			list.add(conn);
		}
		public void clearWarnings() throws SQLException {
			this.conn.clearWarnings();
			
		}
		public void commit() throws SQLException {
			
			this.conn.commit();
		}
		public Statement createStatement() throws SQLException {
			
			return this.createStatement();
		}
		public Statement createStatement(int resultSetType,
				int resultSetConcurrency) throws SQLException {
			// TODO Auto-generated method stub
			return this.createStatement(resultSetType, resultSetConcurrency);
		}
		public Statement createStatement(int resultSetType,
				int resultSetConcurrency, int resultSetHoldability)
				throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public boolean getAutoCommit() throws SQLException {
			// TODO Auto-generated method stub
			return false;
		}
		public String getCatalog() throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public int getHoldability() throws SQLException {
			// TODO Auto-generated method stub
			return 0;
		}
		public DatabaseMetaData getMetaData() throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public int getTransactionIsolation() throws SQLException {
			// TODO Auto-generated method stub
			return 0;
		}
		public Map<String, Class<?>> getTypeMap() throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public SQLWarning getWarnings() throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public boolean isClosed() throws SQLException {
			// TODO Auto-generated method stub
			return false;
		}
		public boolean isReadOnly() throws SQLException {
			// TODO Auto-generated method stub
			return false;
		}
		public String nativeSQL(String sql) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public CallableStatement prepareCall(String sql) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public CallableStatement prepareCall(String sql, int resultSetType,
				int resultSetConcurrency) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public CallableStatement prepareCall(String sql, int resultSetType,
				int resultSetConcurrency, int resultSetHoldability)
				throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public PreparedStatement prepareStatement(String sql)
				throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public PreparedStatement prepareStatement(String sql,
				int autoGeneratedKeys) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public PreparedStatement prepareStatement(String sql,
				int[] columnIndexes) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public PreparedStatement prepareStatement(String sql,
				String[] columnNames) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public PreparedStatement prepareStatement(String sql,
				int resultSetType, int resultSetConcurrency)
				throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public PreparedStatement prepareStatement(String sql,
				int resultSetType, int resultSetConcurrency,
				int resultSetHoldability) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public void releaseSavepoint(Savepoint savepoint) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public void rollback() throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public void rollback(Savepoint savepoint) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public void setAutoCommit(boolean autoCommit) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public void setCatalog(String catalog) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public void setHoldability(int holdability) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public void setReadOnly(boolean readOnly) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public Savepoint setSavepoint() throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public Savepoint setSavepoint(String name) throws SQLException {
			// TODO Auto-generated method stub
			return null;
		}
		public void setTransactionIsolation(int level) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
			// TODO Auto-generated method stub
			
		}
		
		
	}
	
	*/
	
	public Connection getConnection() throws SQLException {
		
		if(list.size()>0){
			final Connection conn = list.removeFirst();  //mysqlConnection  close
			System.out.println("     :" + conn + "       :" + list.size());
			//MyConnection myconn = new MyConnection(conn);
			return (Connection) Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler(){

				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					
					String methodname = method.getName();  //  dao        
					if(methodname.equals("close")){
						list.add(conn);
						System.out.println(conn + "      ,     :" + list.size());
						return null;
					}else{
						return method.invoke(conn, args);
					}
				}
				
			});    //dao----connection.createstatement  commit close()
		}else{
			throw new RuntimeException("    ,     !!");
		}
	}

	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	public void setLogWriter(PrintWriter arg0) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	public void setLoginTimeout(int arg0) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	
	
}

2.
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils {
	
	private static Properties prop = new Properties();
	static{
		try{
			InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
			prop.load(in);
			Class.forName(prop.getProperty("driver"));
		}catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));
	}
	
	public static void release(Connection conn,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
			rs.close();
			}catch (Exception e) {}
		}
		
		if(st!=null){
			try{
			st.close();
			}catch (Exception e) {}
		}
		
		if(conn!=null){
			try{
			conn.close();
			}catch (Exception e) {}
		}
	}
	
	//       
	public static void update(String sql,Object params[]) throws SQLException{
		Connection conn = null;
		PreparedStatement st = null;
		try{
			conn = getConnection();
			st = conn.prepareStatement(sql);
			for(int i=0;i<params.length;i++){
				st.setObject(i+1, params[i]);
			}
			st.executeUpdate();
		}finally{
			release(conn, st, null);
		}
	}
	//    
	public static Object query(String sql,Object params[],ResultSetHandler rsh) throws SQLException{
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try{
			conn = getConnection();
			st = conn.prepareStatement(sql);
			for(int i=0;i<params.length;i++){
				st.setObject(i+1, params[i]);
			}
			rs = st.executeQuery();
			
			return rsh.handler(rs);
			
		}finally{
			release(conn, st, null);
		}
	}
	
}
DBUtils     :
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

public class Demo1 {
	
	/*
	create database wangs;
	use wangs;
	
	create table account
	(
		id int primary key auto_increment,
		name varchar(20),
		money double
	);
	 
	 
	*/
	

	@Test
	public void insert() throws SQLException {
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "insert into account(name,money) values(?,?)";
		Object params[] = {"aaa",10000};
		qr.update(sql, params);
		
	}

	@Test
	public void update() throws Exception {

		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "update account set money=? where id=?";
		Object params[] = {2000,1};
		qr.update(sql, params);
		
	}

	@Test
	public void delete() throws Exception {
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "delete from account where id=?";
		qr.update(sql, 1);
	}

	@Test
	public void find() throws Exception {
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql= "select * from account where id=?";
		Account a = (Account) qr.query(sql,2, new BeanHandler(Account.class));
		System.out.println(a);
	}

	@Test
	public void getAll() throws SQLException {
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql= "select * from account";
		List list = (List) qr.query(sql, new BeanListHandler(Account.class));
		System.out.println(list);
	}
	
	@Test
	public void batch() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "insert into account(name,money) values(?,?)";
		Object params[][] = new Object[10][];
		for(int i=0;i<10;i++){
			params[i] = new Object[]{"aa"+i,1000+i};
		}
		qr.batch(sql, params);
	}
}

2. なプロセッサ
 
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;


public class Demo2 {
	//        
	
	@Test
	public void testArrayHandler() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from account";
		Object results[] = (Object[]) qr.query(sql, new ArrayHandler());
		System.out.println(Arrays.asList(results));  //toString()
	}
	
	
	@Test
	public void testArrayListHandler() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from account";
		List<Object[]> list =  (List<Object[]>) qr.query(sql, new ArrayListHandler());
		System.out.println(Arrays.asList(list));  //toString()
	}
	
	@Test
	public void testColumnListHandler() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from account";
		List list = (List) qr.query(sql, new MyColumnListHandler("id"));
		System.out.println(list);  //toString()
	}
	
	@Test
	public void testKeyedHandler() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from account";
		Map<Integer,Map<String,Object>> map = (Map) qr.query(sql, new KeyedHandler("id"));
		Set<Entry<Integer, Map<String, Object>>> set = map.entrySet();
		for(Map.Entry<Integer, Map<String, Object>> entry : set){
			System.out.println("key=" + entry.getKey());
			Map<String, Object> innermap = entry.getValue();
			for(Map.Entry<String, Object> innerentry : innermap.entrySet()){
				System.out.print(innerentry.getKey() +"="+ innerentry.getValue() + "       ");
			}
			
			System.out.println();
		}
	}
	
	@Test
	public void testMapHandler() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		
	}
	
	@Test
	public void testMapListHandler() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		
	}
	
	
	//select count(*) from account;
	@Test
	public void testScalarHandler() throws Exception{
		
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select count(*) from account";
		long count = (Long)qr.query(sql, new ScalarHandler(1));
		System.out.println(count);
		
	}
	
}

class MyColumnListHandler implements ResultSetHandler{

	private String columnName;
	public MyColumnListHandler(String columnName){
		this.columnName = columnName;
	}
	
	public Object handle(ResultSet rs) throws SQLException {  //    
		List list = new ArrayList();
		while(rs.next()){
			list.add(rs.getObject(columnName));
		}
		return list;
	}
	
}