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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

單獨(dú)使用jdbc編程問題

2019-11-11 05:06:40
字體:
供稿:網(wǎng)友

單獨(dú)使用jdbc編程問題

Public static void main(String[] args) { Connection connection = null; PReparedStatement preparedStatement = null; ResultSet resultSet = null; try { //加載數(shù)據(jù)庫驅(qū)動 Class.forName("com.MySQL.jdbc.Driver"); //通過驅(qū)動管理類獲取數(shù)據(jù)庫鏈接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "111111"); //定義sql語句 ?表示占位符 String sql = "select * from user where username = ?"; //獲取預(yù)處理statement preparedStatement = connection.prepareStatement(sql); //設(shè)置參數(shù),第一個參數(shù)為sql語句中參數(shù)的序號(從1開始),第二個參數(shù)為設(shè)置的參數(shù)值 preparedStatement.setString(1, "王五"); //向數(shù)據(jù)庫發(fā)出sql執(zhí)行查詢,查詢出結(jié)果集 resultSet = preparedStatement.executeQuery(); //遍歷查詢結(jié)果集 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編程步驟

加載數(shù)據(jù)庫驅(qū)動創(chuàng)建并獲取數(shù)據(jù)庫鏈接創(chuàng)建jdbc statement對象設(shè)置sql語句設(shè)置sql語句中的參數(shù)(使用preparedStatement)通過statement執(zhí)行sql并獲取結(jié)果對sql執(zhí)行結(jié)果進(jìn)行解析處理釋放資源(resultSet、preparedstatement、connection)

jdbc編程總結(jié)

數(shù)據(jù)庫鏈接創(chuàng)建、釋放頻繁造成系統(tǒng)資源浪費(fèi)從而影響系統(tǒng)性能,如果使用數(shù)據(jù)庫鏈接池可解決此問題。Sql語句在代碼中硬編碼,造成代碼不易維護(hù),實(shí)際應(yīng)用sql變化的可能較大,sql變動需要改變java代碼使用preparedStatement向占有位符號傳參數(shù)存在硬編碼,因?yàn)閟ql語句的where條件不一定,可能多也可能少,修改sql還要修改代碼,系統(tǒng)不易維護(hù)。對結(jié)果集解析存在硬編碼(查詢列名),sql變化導(dǎo)致解析代碼變化,系統(tǒng)不易維護(hù),如果能將數(shù)據(jù)庫記錄封裝成pojo對象解析比較方便
上一篇:LINUX Read命令

下一篇:Dungeon Master [bfs]

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 梓潼县| 福安市| 当阳市| 平舆县| 博白县| 京山县| 孝昌县| 丹东市| 晋州市| 永顺县| 抚顺市| 吴旗县| 卢氏县| 榕江县| 朔州市| 凤凰县| 湄潭县| 余姚市| 竹溪县| 富民县| 称多县| 镇坪县| 南郑县| 扶风县| 白朗县| 城步| 基隆市| 卢氏县| 盐城市| 宜良县| 屯留县| 邢台市| 灵寿县| 双柏县| 甘谷县| 天门市| 拉孜县| 玛沁县| 南涧| 定兴县| 荣昌县|