JDBC入門(1),jdbc入門

來源:互聯網
上載者:User

JDBC入門(1),jdbc入門

   JDBC(Java DataBase Connectivity,java資料庫連接)是一種用於執行SQL語句的Java API,可以為多種關聯式資料庫提供統一訪問,它由一組用Java語言編寫的類和介面組成。JDBC提供了一種基準,據此可以構建更進階的工具和介面,使資料庫開發人員能夠編寫資料庫應用程式,同時,JDBC也是個商標名。

一、Java串連資料庫樣本:

1、步驟:

  • 導jar包:驅動。
  • 載入驅動類:Class.forName("類名");
  • 給出url、username、password,其中url背下來。
  • 使用DriverManager類來得到Connection對象。
 1 public class Demo1 { 2     /** 3      * ClassNotFoundException: 4      * 沒有匯入驅動包 5      * 6      * SQLException: 7      *  檢查三個參數:url、username、password是否正確 8      *  檢查是否開啟了mysql伺服器。 9      *10      */11     @Test12     public void fun1() throws ClassNotFoundException,SQLException{13         /**14          * jdbc四大配置參數15          *   driverClassName:com.mysql.jdbc.Driver16          *   url:jdbc:mysql://localhost:3306/資料庫名17          *   username:root18          *   password:19          */20         Class.forName("com.mysql.jdbc.Driver");//載入驅動類(註冊驅動)21 22         //使用url、username、password,得到連線物件23         Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb_1","root","");24         System.out.println(con);25     }26 }

2、基本異常

未導驅動包:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ;

資料庫不存在:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'mydb';

連接埠錯誤:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure;

密碼錯誤:java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES);

使用者不存在:java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES);

二、JDBC原理

Class.forName("com.mysql.jdbc.Driver");//此據等同於以下面兩句,與最後一句的邏輯關係com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver;DriverManager.registerDriver(driver);Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb_1","root","");

  所有的java.sql.Driver實作類別,都提供了static塊,塊內的代碼就是把自己註冊到DriverManage中,如com.mysql.jdbc.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()    }}

  JDBC 4.0之後,每個驅動jar包中,在META-INF/services目錄下提供了一個名為java.sql.Driver的檔案,檔案的內容就是該介面的實作類別名稱。串連資料庫例子中,第20行“Class.forName("com.mysql.jdbc.Driver");”可省略不寫。

三、使用JDBC對資料庫進行簡單的增刪改查操作樣本

  1 package demo2;  2   3 import org.junit.Test;  4 import java.sql.*;  5   6 public class Demo2 {  7     /*  8     * 對資料庫進行增、刪、改操作  9     * */ 10     @Test 11     public void fun1() throws ClassNotFoundException,SQLException { 12         /* 13         * 一、得到Connection 14         * 1、準備四個參數 15         * 2、載入驅動類 16         * 3、得到Connection 17         * */ 18  19         String driverClassName = "com.mysql.jdbc.Driver"; 20         //jdbc協議的格式,jdbc:工商的名稱:子協議(由工商自己來規定) 21         //對mysql而言,它的子協議結構://主機:連接埠號碼/資料庫名稱 22         String url = "jdbc:mysql://localhost:3306/mydb1"; 23         String username = "root"; 24         String password = ""; 25         //載入驅動類 26         Class.forName(driverClassName); 27         //使用DriverManager,以及剩下的三個參數,得到Connection 28         Connection con = DriverManager.getConnection(url, username, password); 29         /* 30         * 二、對資料庫做增刪改 31         *1、通過Connection對象建立Statement 32         *  Statement 語句的發送器,它的功能就是向資料庫發送sql語句, 33         *2、調用它的int executeUpdate(String sql),它可以發送DML、DDL 34         * */ 35         Statement stmt = con.createStatement(); 36 //        String sql = "INSERT INTO stu VALUES('0003','wangwu',88,'male')"; 37 //        String sql = "UPDATE stu SET name='zhaoliu',age=22,gender='female' WHERE " + 38 //                "number='0003'"; 39         String sql = "DELETE FROM stu"; 40         int r = stmt.executeUpdate(sql); 41         System.out.println(r); 42     } 43     /* 44      * 執行查詢操作 45      * */ 46      @Test 47     public void fun2() throws ClassNotFoundException,SQLException { 48  49          /* 50          * 一、得到Connection 51          * 二、得到Statement,發送select語句 52          * 三、對查詢返回的"表格"進行解析 53          * */ 54          /* 55          * 一、得到串連 56          * */ 57          String driverClassName = "com.mysql.jdbc.Driver"; 58          String url = "jdbc:mysql://localhost:3306/mydb1"; 59          String username = "root"; 60          String password = ""; 61  62          Class.forName(driverClassName); 63          Connection con = DriverManager.getConnection(url,username,password); 64          /* 65          * 二、得到Statement,執行select語句 66          * */ 67          Statement stmt = con.createStatement(); 68          /* 69          *調用Statement的ResultSet rs = executeQuery(String querySql); 70          * */ 71          ResultSet rs = stmt.executeQuery("SELECT * FROM emp"); 72          /* 73          * 三、解析ResultSet 74          * 1、把行游標移動到第一行,可以調用next()方法完成。 75          * */ 76          while (rs.next()) { //把游標向下移動一行,並判斷下一行是否存在 77              int empno = rs.getInt(1);//通過列編號來擷取該列的值 78              String ename = rs.getString("ename");//通過列名稱來擷取該列的值 79              double sal = rs.getDouble("sal"); 80  81              System.out.println(empno+","+ename+","+sal); 82          } 83          /* 84          * 四、關閉資源 85          * 倒關 86          * */ 87          rs.close(); 88          stmt.close(); 89          con.close();//必須關,不關就死。 90     } 91     //正常化 92     @Test 93     public void fun3() throws Exception { 94         Connection con = null;//定義引用 95         Statement stmt = null; 96         ResultSet rs = null; 97         try { 98             //一、得到Connection 99             String driverClassName  = "com.mysql.jdbc.Driver";100             String url = "jdbc:mysql://localhost:3306/mydb1";101             String username = "root";102             String password = "";103             Class.forName(driverClassName);104             con = DriverManager.getConnection(url,username,password);//執行個體化105             //二、建立Statement106             stmt = con.createStatement();107             String sql = "SELECT * FROM emp";108             rs = stmt.executeQuery(sql);//執行個體化109             //三、迴圈遍曆rs,列印其中資料110             //getString()和getObject()是通用的111             int count = rs.getMetaData().getColumnCount();112             while (rs.next()) {113                 for (int i = 1; i <= count; i++) {114                     System.out.print(rs.getString(i));115                     if (i<count) {116                         System.out.print(",");117                     }118                 }119                 System.out.println();120             }121 122         } catch (Exception e) {123             throw new RuntimeException(e);124         } finally {125             //為了防止null 指標異常發生,使用判斷語句126             if(rs != null) rs.close();127             if(stmt != null) stmt.close();128             if(con != null) con.close();129         }130     }131 }

 

聯繫我們

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