jdbc-mysql基礎 把查詢到的結果集封裝成Map的形式

來源:互聯網
上載者:User

標籤:port   tables   pack   ast   ble   自己   處理   部落格   super   

禮悟:
     好好學習多思考,尊師重道存感恩。葉見尋根三二一,江河湖海同一體。
          虛懷若穀良心主,願行無悔給最苦。讀書鍛煉強身心,誠勸且行且珍惜。

 

 

  資料、資料,命根就在資料。雲端運算、AI等技術,都是以資料為基礎。操作資料庫一定要謹慎小心。給最苦 這裡的代碼,看看就好,要有自己的判斷。遇到抉擇,要不恥上下問,三思而後行。
                             javaSE:8
                              mysql:5.7.14
     mysql-connector-java:5.1.44
                  MySQL-Front:5.4
                                    os:windows7 x64
                                   ide:MyEclipse 2017

 

 

特製的異常類

package com.jizuiku;/** * 這個類很重要,即完成了拋異常的動作、通過編譯,又可以使資料邏輯層的介面保持簡潔。 *  * @author 部落格園-給最苦 * @version V17.11.08 */public class DaoException extends RuntimeException {/** *  */private static final long serialVersionUID = 1L;public DaoException() {// TODO Auto-generated constructor stub}public DaoException(String message) {super(message);// TODO Auto-generated constructor stub}public DaoException(Throwable cause) {super(cause);// TODO Auto-generated constructor stub}public DaoException(String message, Throwable cause) {super(message, cause);// TODO Auto-generated constructor stub}public DaoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);// TODO Auto-generated constructor stub}}

 

JDBCUtils類

package com.jizuiku;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** *  *  * @author 給最苦 * @version V17.11.07 */public final class JDBCUtils {/** * url格式 -> jdbc:子協議:子名稱//主機名稱:連接埠號碼/資料庫的名字?屬性名稱=屬性值&屬性名稱=屬性值 * configString變數中有多個參數,需要深入地去研究它們的具體含義 */private static String configString = "?useUnicode=true&characterEncoding=utf8&useSSL=true";private static String url = "jdbc:mysql://localhost:3306/jdbcforjava" + configString;// 本地的mysql資料庫(無子名稱) 連接埠號碼3306 資料庫jdbcforjavaprivate static String user = "root";private static String password = "";// 工具類,直接使用,不可生對象private JDBCUtils() {}// 註冊驅動,這裡應用的是static代碼塊只執行一次的特點static {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blockthrow new ExceptionInInitializerError(e);}}/** * 擷取與指定資料庫的連結 *  */public static Connection getConnection() throws SQLException {return DriverManager.getConnection(url, user, password);}/** * 釋放三種資源ResultSet PreparedStatement Connection *  */public static void free(ResultSet rs, PreparedStatement ps, Connection con) {try {if (rs != null) {rs.close();}} catch (SQLException e) {// TODO Auto-generated catch blockthrow new DaoException(e.getMessage(), e);} finally {try {if (ps != null) {ps.close();}} catch (SQLException e) {// TODO Auto-generated catch blockthrow new DaoException(e.getMessage(), e);} finally {try {if (con != null) {con.close();}} catch (SQLException e) {// TODO Auto-generated catch blockthrow new DaoException(e.getMessage(), e);}}}}}

 

資料庫中的內容

 

測試類別

package com.jizuiku;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;/** *  *  * @author 部落格園-給最苦 * @version V17.11.09 */public class Demo {public static void main(String[] args) {// 注意看,這裡有個坑 -> name as username// 列名與列的別名String sql = "select id,name as username,quantity,time,price from book";List<Map<String,Object>> result = test(sql);System.out.println("查詢到的結果集是:");System.out.println(result);}public static List<Map<String,Object>> test(String sql) {Connection con = null;PreparedStatement ps = null;ResultSet rs = null;ResultSetMetaData rsmd = null;try {// 註冊驅動並建立串連con = JDBCUtils.getConnection();// 建立語句 並 對sql語句進行一些預先處理ps = con.prepareStatement(sql);// 執行語句rs = ps.executeQuery();// 得到列的個數rsmd = rs.getMetaData();int colCount = rsmd.getColumnCount();// 因為要儲存列的名字,所以要與列的個數相同String[] colNames = new String[colCount];/* 裝上列的名字 * getColumnLabel 別名 * getColumnLabel()方法的索引是從1開始的。給最苦 寫成從0開始,就拋了異常。 */for (int i = 1; i <= colCount; i++) {colNames[i-1] = rsmd.getColumnLabel(i);}System.out.println("儲存列的別名的數組內容是:");System.out.println(Arrays.toString(colNames));      // 這裡的泛型聲明也是有技巧的。HashMap<String,Object> data = null;List<Map<String,Object>> datas = new ArrayList<Map<String,Object>>();// 把查詢到的結果裝入datas中while(rs.next()){data = new HashMap<String, Object>();for (int i = 0; i < colCount; i++) {//        key             valuedata.put(colNames[i], rs.getObject(colNames[i]));}datas.add(data);}// 返回結果return datas;} catch (SQLException e) {throw new DaoException(e);} finally {// 釋放資源JDBCUtils.free(rs, ps, con);}}}

 

控制台輸出的結果

儲存列的別名的數組內容是:[id, username, quantity, time, price]查詢到的結果集是:[{quantity=170, price=60.00, id=2, time=2017-11-06 00:00:00.0, username=莊子}, {quantity=1020, price=99.87, id=4, time=2017-11-10 00:00:00.0, username=孟子}, {quantity=170, price=90.00, id=5, time=2017-11-03 00:00:00.0, username=傷寒雜病論}, {quantity=60, price=99.99, id=6, time=2017-11-16 00:00:00.0, username=孟子}, {quantity=190, price=110.00, id=7, time=2017-11-01 00:00:00.0, username=大學}, {quantity=200, price=40.00, id=8, time=2017-11-12 00:00:00.0, username=周易}, {quantity=195, price=40.00, id=9, time=2017-10-10 00:00:00.0, username=參同契}, {quantity=185, price=45.00, id=10, time=2017-09-09 00:00:00.0, username=金剛經}, {quantity=200, price=99.99, id=13, time=2017-01-01 00:00:00.0, username=地藏菩薩本願經}, {quantity=130, price=99.87, id=14, time=2017-11-08 00:00:00.0, username=孟子}, {quantity=60, price=99.99, id=17, time=2017-11-16 00:00:00.0, username=孟子}, {quantity=60, price=99.99, id=18, time=2017-11-16 00:00:00.0, username=孟子}, {quantity=60, price=99.99, id=19, time=2017-11-16 00:00:00.0, username=孟子}]

 

  註:這篇博文中有許多 小知識點,可以多看看。然後就是,操作資料庫要謹慎小心,給最苦 這裡的代碼 看看就好。

 

 

學習資源:itcast和itheima視頻庫。如果您有公開的資源,可以分享給我的話,用您的資源學習也可以。
博文是觀看視頻後,融入思考寫成的。博文好,是老師講得好。博文壞,是 給最苦 沒認真。

jdbc-mysql基礎 把查詢到的結果集封裝成Map的形式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.