mybatis(1)對原生態jdbc程序(單獨使用jdbc開發)問題總結

原生態jdbc程序

Public static void main(String[] args) {
			Connection connection = null;
			//預編譯的statement,使用預編譯的statement會提升數據庫的性能,客戶端將sql語句傳到數據庫的時候,數據庫會先編譯sql語句,存放在緩存中。
			PreparedStatement preparedStatement = null;
			ResultSet resultSet = null;
			
			try {
				//加載數據庫驅動
				Class.forName("com.mysql.jdbc.Driver");
				
				//通過驅動管理類獲取數據庫鏈接
				connection =  DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "mysql");
				//定義sql語句 ?表示佔位符
			String sql = "select * from user where username = ?";
				//獲取預處理statement
				preparedStatement = connection.prepareStatement(sql);
				//設置參數,第一個參數爲sql語句中參數的序號(從1開始),第二個參數爲設置的參數值
				preparedStatement.setString(1, "王五");
				//向數據庫發出sql執行查詢,查詢出結果集
				resultSet =  preparedStatement.executeQuery();
				//遍歷查詢結果集
				while(resultSet.next()){
					System.out.println(resultSet.getString("id")+"  "+resultSet.getString("username"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				//釋放資源
				if(resultSet!=null){
					try {
                        resultSet.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(preparedStatement!=null){
					try {
						preparedStatement.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(connection!=null){
					try {
						connection.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

		}

問題總結:

1、數據庫連接,使用時就創建,不使用立即釋放,對數據庫進行頻繁連接開啓和關閉,造成數據庫資源浪費,影響 數據庫性能。

設想:使用數據庫連接池管理數據庫連接。

2、將sql語句硬編碼到java代碼中,如果sql 語句修改,需要重新編譯java代碼,不利於系統維護。

設想:將sql語句配置在xml配置文件中,即使sql變化,不需要對java代碼進行重新編譯。

3、向preparedStatement中設置參數,對佔位符號位置和設置參數值,硬編碼在java代碼中,不利於系統維護。

設想:將sql語句及佔位符號和參數全部配置在xml中。

4、從resutSet中遍歷結果集數據時,存在硬編碼,將獲取表的字段進行硬編碼,,不利於系統維護。

設想:將查詢的結果集,自動映射成java對象。

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章