1. 程式人生 > 其它 >阿里Java學習路線:階段 2:資料庫開發-JDBC資料庫開發入門:課時4:JDBC之程式碼規範化

阿里Java學習路線:階段 2:資料庫開發-JDBC資料庫開發入門:課時4:JDBC之程式碼規範化

技術標籤:阿里Java學習路線

規範化程式碼

所謂規範化程式碼就是無論是否出現異常, 都要關閉 ResultSet, Statement 以及 Connection,如果你還記得IO流的規範化程式碼,那麼下面的程式碼你就明白什麼意思了。

示例:

public void query() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null; // 在try外給出引用的定義
     
        try{
            con = getConnection
(); // 在try內為物件例項化 stmt = con.createStatement(); String sql = "SELECT * FROM user"; rs = stmt.executeQuery(sql); while(rs.next()){ String username = rs.getString(1); // 獲取第一列的值, 引數為列編號或列名 String password = rs.
getString(2); // 獲取第二列的值 System.out.println(username+","+password); } } catch(Exception e){ throw new RuntimeException(e); } finally{ try{ if(rs != null) rs.close(); if(stmt != null) stmt.close
(); if(con != null) con.close(); // 在finally中進行關閉 } catch(SQLException e){ throw new RuntimeException(e); } }

測試類:

    @Test
    public void fun3() throws Exception{
    	Connection con = null; // 定義引用
    	Statement stmt = null;
    	ResultSet rs = null;
    	try {
	    	/*
	    	 * 一、得到連線
	    	 */
			String driverClassName = "com.mysql.jdbc.Driver";
			String url = "jdbc:mysql://localhost:3306/mydb1?characterEncoding=utf8&useSSL=true";
			String username = "root";
			String password = "1234";
			
			Class.forName(driverClassName);
			con = DriverManager.getConnection(url,username,password); // 例項化
			
			/*
			 * 二、建立Statment
			 */
			stmt = con.createStatement();
			String sql = "SELECT * FROM emp";
    		rs = stmt.executeQuery(sql);
    		/*
    		 * 三、迴圈遍歷rs,列印其中資料
    		 * getString()和getObject()是通用的
    		 */
    		while(rs.next()) {
    			System.out.println(rs.getObject(1) + "," + rs.getString("ename") + "," + rs.getDouble("sal"));
    		}
    	} catch (Exception e) {
    		throw new RuntimeException(e);
		} finally {
			// 關閉
            if(rs != null) rs.close();
            if(stmt != null) stmt.close();
            if(con != null) con.close();
		}
    }

在這裡插入圖片描述