Java工具類——jdbc

5517 ワード

javaコードでデータベースを操作します。(本論文はMySQLを例として)
操作は通常6ステップに分けられます。
1.データベースドライバの読み込み
2.データベース接続オブジェクトの作成
3.SQLを実行するステートメントオブジェクトを作成する
4.SQL文を実行する
5.処理結果
6.データベースのリソースを解放する
データベースメーカーは自分のデータベースの特徴に合ったデータベースドライバを実現します。
一般的なデータベース製品の駆動ローディング方式は以下の通りです。
Mysql Class.forName(「comp.mysql.jdbc.Driver」);
Oracle Class.forName(「oracle.jdbc.driver.OracleDriver」);
SQLServer Class.forName(「comp.microsoff.sqlserver.jdbc.SQLServerDriver」);
実際の操作:
本論文ではMySQLを使用して、まずMySQLのjdbcのjarファイルをダウンロードします。本文はmysql-connector-java-51.1.41-bin.jarを使用しています。
パッケージ:
	private static String className,url,user,password;

	/**
	 * 1.    ,     ,     
	 */
	static {
		try {
			// 1.1.                
			Properties pops = new Properties();
			pops.load(UtilsJDBC.class.getResourceAsStream("/jdbc.properties"));
			className = pops.getProperty("className");
			url = pops.getProperty("url");
			user = pops.getProperty("user");
			password = pops.getProperty("password");

			// 1.2.    
			Class.forName(className);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	/**
	 *     
	 * @return	    
	 */
	private static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
複数の人がデータベースを同時に操作する問題を考慮して、静的パラメータurl、user、passwordに値を与えていません。プロファイルjdbc.propertiesを使用して実装されます。設定ファイルからデータを取り出して初期化します。
SQL文オブジェクトを作成します。
よく使われるのはSteementオブジェクトとPreparedStatimentオブジェクトです。
ステージオブジェクト通過
Sttement stmt=conn.createment()
PreparedSttementオブジェクト通過
String sql="select*from students where name=?andsex=?"PreparedSttement ps=conn.preparedSttement(sql);ps.set String(1、「張三」)ps.set String(2,「女」)ここで、パラメータsqlはプレースホルダを持つことができます。
SttementオブジェクトまたはPreparedSttementオブジェクトがexecuteXxx()を呼び出す方法はSQL文をデータベース管理システムに送ります。データベース管理システムが実行した後に結果が戻ります。種類によってsql文と異なるexecuteXxx()方法で返した結果が異なります。結果の処理方法も違います。
Sttementタイプステートメントオブジェクトの実行
booklean b=stmt.execute(sql)//任意のsql文を実行します。
int I=stmt.executeUpdate(sql)//添削を実行するSQL文
ResultSet rs=stmt.executeQuery(sql)/。クエリ文を実行
PreparedSttementタイプのステートメントオブジェクトの実行bootan b=ps.execute()//任意の種類のsql文int I=ps.executeUpdate()//添削タイプsql文ResultSet rs=ps.executeQueryを実行します。検索文の以上を実行すると、添削が見られます。返したのはsql文がデータベースで応答する行数です。クエリーは戻りの結果セットです。ですから、二つのパッケージ方法を書いて区別します。
また、
・createstatementを使用する場合は、executeUpdate(sql)方法に合わせて、ここに入ってきたsqlはプレースホルダを使用してはいけません。
・preparedSttement(sql)を使用する場合は、executeUpdate()を使用する方法に合わせて、ここに入ってきたsqlはプレースホルダを使用することができます。
  ··また、sqlをプレースホルダまたはプレースホルダで区別する必要があります。あるいは重載方法を書きます。
ここでは、preparedSttement(sql)を使用する例として、可変パラメータが入ってきて、再負荷を回避し、プレースホルダを使用する動作を最適化する。
	/**
	 *    
	 * @param sql	sql     ,     ?
	 * @param args	      ,       
	 * @return	         
	 */
	static public int updata(String sql,Object...args){
		Connection conn = null;
		PreparedStatement ps=null;
		int rows = 0;
		try {
			conn=getConn();
			ps=conn.prepareStatement(sql);
			
			//       ,      1  ,     0  
			if(args!=null && args.length>0){
				for(int i=0;i0) {
			System.out.println("    ");
		}else {
			System.out.println("    ");
		}
		return rows;
	}
	/**
	 *   
	 *      ,             
	 * @param sql	sql    ,     ?
	 * @param obj	     
	 * @return	      list  
	 */
	public static List> query(String sql,Object...args) {
		Connection conn = null;
		PreparedStatement ps=null;
		ResultSet res=null;
		
		List> list=new ArrayList>();
		try {
			conn=getConn();
			ps = conn.prepareStatement(sql);	
			//      null     0  sql    ?   
			//       ,      1  ,     0  
			if(args!=null && args.length>0){ //1
				for(int i=0;i rowData=new HashMap();
				
				//    1  
				for (int i = 1; i <= count; i++) {
					//                   resmd.getColumnType();//    		resmd.getColumnTyoeName();//      
					String cname=resmd.getColumnLabel(i);
					Object cvalue=res.getObject(cname);
					rowData.put(cname, cvalue);
				}
				list.add(rowData);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(res, ps, conn);
		}
		return list;
	}
最後に、リソースを閉じます。もちろん、上述の方法では、SQL操作を実行した後、この方法を呼び出してリソースをクローズしました。
	/**
	 *     
	 * @param res	   
	 * @param stmt	  
	 * @param conn	  
	 * @throws SQLException
	 */
	private static void close(ResultSet res, Statement stmt, Connection conn){
		try {
			if (res != null) {
				res.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
 上記の照会方法では、結果セットを処理し、結果セットをリストセットに入れた。
このようにする理由は、結果集を処理する前に、資源を閉鎖することができないからです。結果セットは処理できません。
調べた後、結果をリストに入れた後、すぐに資源を閉鎖しました。なお、クエリー結果の処理は、リストの動作によって実行されてもよい。
このようにしてConnectionの使用原則に適合しています。つまり、できるだけ遅く作成して、できるだけ早く釈放してください。データベースの接続が限られていますので、直ちに釈放しないとシステムが崩壊します。