1. 程式人生 > >淺入淺出JDBC————1分鐘瞭解JDBC

淺入淺出JDBC————1分鐘瞭解JDBC

一.瞭解基本的幾個jdbc需要的類

1.1DriverManager類

 DriverManager類是一個jdbc的驅動服務類。通常使用該類獲得一個Connection物件,得到一個數據庫的連結。

1.2.Connection類

 每一個Coonection的物件都是一個數據庫的連結物件,代表了一個物理會話。

1.3. Statement類

 執行sql語句的工具介面。

1.4.PreparedStatement類

Statement類的子介面,一個預編譯的Statment物件。

1.5.ResultSet類

查詢結果集類

二.進行jdbc程式設計

2.1步驟

1.載入資料庫驅動

 使用Class類的forName方法來載入資料庫連結驅動。

 程式碼例項:

String dirver ="com.mysql.jdbc.Driver";//載入資料庫驅動
Class.forName(dirver);

 2.獲取資料庫的連結

 通過上面的驅動服務類來獲取資料庫連結,使用DriverManager類的getConnection()方法來連結,得到一個數據庫的物理會話。

 getConnection(String url,String user,String pass)方法解析:

 該方法返回一個Connection物件,引數中的url是指資料庫的url。

 mysql的url為:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false

 程式碼例項:

String url="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
String user="root";
String password="4399";
conn = DriverManager.getConnection(url,user,password);

3.通過Connection物件建立一個Statement物件。

在這裡有三種Statement物件來建立,基本的Statement物件,還有就是預編譯的Statement物件prepareStatement

和執行儲存過程的CallableStatement物件

分別來看看三種物件的建立方式:

        //載入驅動
        Class.forName("com.mysql.jdbc.Driver");
        //獲得一個物理回話
        Connection conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false","root","4399");
        //得到一個普通的Statement物件
        Statement stat=conn.createStatement();
        //得到預編譯物件
        PreparedStatement pre_stat=conn.prepareStatement("select * form students");
        String str="{call pro_getCountById(?, ?, ?)}";//儲存過程
        //執行儲存過程的物件
        CallableStatement call_stat = conn.prepareCall(str);

4.使用Statement物件來執行sql語句

三種方法來執行sql語句:

1.execute()可以執行任何sql語句。

2.executeUpdate()執行DML語句和DDL語句,DDL語句返回0,DML語句返回影響行數。

3.executeQuery()只能執行查詢語句,返回查詢結果集ResultSet。

程式碼例項:

stat.executeUpdate("drop table if exists tab1");//執行DDL語句
stat.executeUpdate("insert into tabl values (10,'zhansan') ");//執行DML語句
ResultSet res=stat.executeQuery("select * from tab1");//執行DQL

5.操作結果集

理解ResultSet類:(引用)

6.回收資料庫資源

需要關閉的資源:ResultSet、Statement、Connection