jdbc-mysql基礎 註冊驅動 Class.forName

來源:互聯網
上載者:User

標籤:連接埠   obj   異常   highlight   開啟   java   drive   簡潔   recommend   

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

 

 

  資料、資料,命根就在資料。雲端運算、AI等技術,都是以資料為基礎。操作資料庫一定要謹慎小心。網上關於資料庫操作的代碼,看看就好,給最苦 這裡的代碼也是一樣。遇到抉擇,要不恥上下問。
                             javaSE:8
                              mysql:5.7.14
     mysql-connector-java:5.1.44
                                    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.SQLException;/** * 示範類 *  * @author 部落格園-給最苦 * @version V2017.11.13 */public class Demo {public static void main(String[] args) {Connection conn = null;PreparedStatement ps= null;ResultSet rs = null;try {// 得到連結conn = JDBCUtils.getConnection();// 要把列名寫出來,目的方便後續的取資料  String sql = "select id,name,quantity,time,price from book";ps = conn.prepareStatement(sql);// 執行語句 因為執行的語句會返回多行多列,所以使用executeQuery語句rs = ps.executeQuery();// 查詢並輸出資料while (rs.next()) {System.out.println(rs.getObject("id") + " " +    rs.getObject("name") + " " +    rs.getObject("quantity") + " "+    rs.getObject("time") + " " +    rs.getObject("price"));}} catch (SQLException e) {// TODO Auto-generated catch blockthrow new DaoException(e.getMessage(),e);}// 釋放資源JDBCUtils.free(rs,ps,conn);}}

 

效果展示

 

看完示範之後,你是否生出了這樣的疑問:為什麼呢?Class.forName()就能註冊驅動了,什麼原理? 請看下面地分解。

  找原始碼

 

 

  開啟看看

/*  Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.  The MySQL Connector/J is licensed under the terms of the GPLv2  <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.  There are special exceptions to the terms and conditions of the GPLv2 as it is applied to  this software, see the FOSS License Exception  <http://www.mysql.com/about/legal/licensing/foss-exception.html>.  This program is free software; you can redistribute it and/or modify it under the terms  of the GNU General Public License as published by the Free Software Foundation; version 2  of the License.  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.  You should have received a copy of the GNU General Public License along with this  program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth  Floor, Boston, MA 02110-1301  USA */package com.mysql.jdbc;import java.sql.SQLException;/** * The Java SQL framework allows for multiple database drivers. Each driver should supply a class that implements the Driver interface *  * <p> * The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to * connect to the target URL. *  * <p> * It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast * quantities of supporting code. *  * <p> * When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a * driver by doing Class.forName("foo.bah.Driver") */public class Driver extends NonRegisteringDriver implements java.sql.Driver {    //    // Register ourselves with the DriverManager    //    static {        try {            java.sql.DriverManager.registerDriver(new Driver());        } catch (SQLException E) {            throw new RuntimeException("Can‘t register driver!");        }    }    /**     * Construct a new driver and register it with DriverManager     *      * @throws SQLException     *             if a database error occurs.     */    public Driver() throws SQLException {        // Required for Class.forName().newInstance()    }}

 

  通過類的名字,將類裝載到虛擬機器中。一裝載就會調用類的static代碼塊,就是通過這個機制來實現註冊的

 

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

jdbc-mysql基礎 註冊驅動 Class.forName

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.