国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

單獨使用jdbc編程問題

2019-11-11 04:28:19
字體:
來源:轉載
供稿:網友

單獨使用jdbc編程問題

Public static void main(String[] args) { Connection connection = null; 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", "111111"); //定義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(); } } } }

jdbc編程步驟

加載數據庫驅動創建并獲取數據庫鏈接創建jdbc statement對象設置sql語句設置sql語句中的參數(使用preparedStatement)通過statement執行sql并獲取結果對sql執行結果進行解析處理釋放資源(resultSet、preparedstatement、connection)

jdbc編程總結

數據庫鏈接創建、釋放頻繁造成系統資源浪費從而影響系統性能,如果使用數據庫鏈接池可解決此問題。Sql語句在代碼中硬編碼,造成代碼不易維護,實際應用sql變化的可能較大,sql變動需要改變java代碼使用preparedStatement向占有位符號傳參數存在硬編碼,因為sql語句的where條件不一定,可能多也可能少,修改sql還要修改代碼,系統不易維護。對結果集解析存在硬編碼(查詢列名),sql變化導致解析代碼變化,系統不易維護,如果能將數據庫記錄封裝成pojo對象解析比較方便
上一篇:C# SendKeys用法

下一篇:二分

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 叶城县| 名山县| 牙克石市| 文山县| 三穗县| 长春市| 库伦旗| 富民县| 昌吉市| 都兰县| 怀仁县| 衡阳市| 土默特左旗| 奉新县| 沂源县| 怀集县| 隆回县| 玉屏| 香格里拉县| 旅游| 济宁市| 安福县| 双城市| 诸暨市| 合作市| 清水河县| 博罗县| 广水市| 阿坝县| 师宗县| 博爱县| 揭西县| 清新县| 蚌埠市| 柳江县| 桓仁| 称多县| 高青县| 蒙自县| 镇宁| 宁德市|