程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> JDBC數據庫的應用操作總結

JDBC數據庫的應用操作總結

編輯:MySQL綜合教程

JDBC數據庫的應用操作總結。本站提示廣大學習愛好者:(JDBC數據庫的應用操作總結)文章只能為提供參考,不一定能成為您想要的結果。以下是JDBC數據庫的應用操作總結正文


JDBC是一組可以或許履行SQL語句的API

因為傳統的數據庫操作方法須要法式員控制各個分歧的數據庫的API,極端未便

是以java界說了JDBC這一尺度的接口和類,為法式員操作數據庫供給了同一的方法

JDBC的操作方法比擬單一,由五個流程構成:

1.經由過程數據庫廠商供給的JDBC類庫向DriverManager注冊數據庫驅動

2.應用DriverManager供給的getConnection()辦法銜接到數據庫

3.經由過程數據庫的銜接對象的createStatement辦法樹立SQL語句對象

4.履行SQL語句,並將成果聚集前往到ResultSet中

5.應用while輪回讀取成果

6.封閉數據庫資本

上面來看看詳細操作Mysql數據庫的辦法


預備任務

起首我們須要樹立一個數據庫和一張簡略的表

mysql> create database person;
Query OK, 1 row affected (0.00 sec)

mysql> use person;
Database changed
mysql> create table student(
    -> id int,
    -> name varchar(20),
    -> birth year
    -> ) default charset=utf8;
Query OK, 0 rows affected (0.10 sec)

然後往外面拔出幾條數據

mysql> insert into student values
    -> (1,'張三',1990),
    -> (2,'李四',1991),
    -> (3,'王五',1992);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

如許一張簡略的表就建好了

mysql> select * from student;
+------+--------+-------+
| id   | name   | birth |
+------+--------+-------+
|    1 | 張三   |  1990 |
|    2 | 李四   |  1991 |
|    3 | 王五   |  1992 |
+------+--------+-------+
 rows in set (0.00 sec)

接上去,去mysql官網下載數據庫銜接器這個包

個中這個包外面含有一份文檔,外面羅列了根本的應用辦法,可以參考

我們的操作也是依照這份文檔中的內容停止,然後最重要的處所就是導入這個jar包

為了操作便利,這裡應用eclipse來導入

右鍵項目-->構件途徑-->添加內部歸檔,添加好了以後以下所示

如今我們正式開端應用java來操作mysql數據庫

JDBC操作實例1:最簡略的查詢操作

import java.sql.*;

public class Demo {
    //為了代碼緊湊性,臨時拋出一切異常
    public static void main(String[] args) throws Exception {
        //注冊數據庫驅動
        Class.forName("com.mysql.jdbc.Driver");
        //樹立數據庫銜接
        //參數一:jdbc:mysql//地址:端口/數據庫,參數二:用戶名,參數三:暗碼
        Connection conn = DriverManager.getConnection
                ("jdbc:mysql://localhost:3306/person","root","admin");
        //創立SQL語句
        Statement st = conn.createStatement();
        //履行語句,前往成果
        ResultSet rt = st.executeQuery("show tables");
        //輪回掏出成果
        while(rt.next()) {
            //獲得字段
            System.out.println(rt.getString("Tables_in_person"));
        }
        //封閉資本,最早翻開的最初關
        rt.close();
        st.close();
        conn.close();
    }
}

運轉成果:student

如斯即可履行show tables語句查詢出以後數據庫含有若干張表

個中rt.getString()辦法是獲得字段,這點須要留意

封閉資本的方法也與以往相反

不外,下面的操作方法靈巧性不年夜,而且不嚴謹


實例2:優化的查詢操作

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";
        String sql = "select * from student";

        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //履行查詢語句,別的也能夠用execute(),代表履行任何SQL語句
            rs = st.executeQuery(sql);
            while(rs.next()) {
                System.out.println(rs.getObject(1) + "  " +
                        rs.getObject(2) + "  " + rs.getInt("birth"));
            }
        //分離捕捉異常
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                //斷定資本能否存在
                if(rs != null) {
                    rs.close();
                    //顯示的設置為空,提醒gc收受接管
                    rs = null;
                }
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

運轉成果:

這裡把異常給分離捕捉了,而且相干的字符串全體用變量界說

須要留意下輪回掏出數據外面的getInt()辦法,此處必需曉得類型和字段能力掏出

假如不曉得可使用getObject(1)掏出第一列,getObject(2)掏出第二列,以此類推

實例3:自界說變量拔出到數據庫

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {
    public static void main(String[] args) {
        //參數檢討
        if (args.length != 3) {
            System.out.println("參數情勢纰謬");
            System.exit(0);
        }
        String id = args[0];
        String name = args[1];
        String birth = args[2];
        String sql = "insert into student values(" + id + ",'" + name +
                "'," + "'" + birth + "')";
        System.out.println(sql);

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //留意,此處是excuteUpdate()辦法履行
            st.executeUpdate(sql);       
        //分離捕捉異常
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

運轉成果:

這裡運轉須要設置自變量,窗口中右鍵-->運轉方法-->運轉設置裝備擺設

然後在自變量外面寫4 susan 1993,我沒有寫中文,由於發生亂碼,今朝還不清晰緣由

須要留意的是,履行拔出的SQL語句比擬難寫,最好是打印出SQL語句用以檢討

實例4:PreparedStatement運用

從下面的Demo可以看到,拔出數據的時刻,SQL操作相當未便

這裡可使用PreparedStatement對象來簡化SQL語句的樹立

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Demo {

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("參數情勢纰謬");
            System.exit(0);
        }
        String id = args[0];
        String name = args[1];
        String birth = args[2];

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        //聲明PreparedStatement對象的援用
        PreparedStatement pst = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            //應用?取代變量
            pst = conn.prepareStatement("insert into student values (?,?,?)");
            //給指定參數的地位設定變量
            pst.setString(1, id);
            pst.setString(2, name);
            pst.setString(3, birth);
            pst.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(pst != null) {
                    pst.close();
                    pst = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

運轉成果:

實例5:Batch批處置

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //添加批處置
            st.addBatch("insert into student values(6,'Jerry','1995')");
            st.addBatch("insert into student values(7,'Greg','1996')");
            st.addBatch("insert into student values(8,'Ryan','1997')");
            //履行批處置
            st.executeBatch();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

運轉成果:

批處置比擬簡略,只需先樹立Statement對象,然後逐一添加批處置便可

最初應用executeBatch()辦法履行批處置

另外,PreparedStatement對象也能夠應用批處置

PreparedStatement ps = conn.prepareStatement("insert into student values(?,?,?)");
ps.setInt(1,8);
ps.setString(2,"GG");
ps.setString(3,"1996");
ps.addBatch();
ps.executeBatch();

實例6:Transaction事務處置

事務處置是請求sql以單位的情勢更新數據庫,請求其確保分歧性

如銀行的轉賬營業,一方轉出後,另外一方則增長

假如湧現異常,那末一切的操作則會回滾

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            //撤消主動提交
            conn.setAutoCommit(false);
            st = conn.createStatement();
            st.addBatch("insert into student values(6,'Jerry','1995')");
            st.addBatch("insert into student values(7,'Greg','1996')");
            st.addBatch("insert into student values(8,'Ryan','1997')");
            st.executeBatch();
            //提交後設置主動提交
            conn.commit();
            conn.setAutoCommit(true);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

            if(conn != null) {
                try {
                    //湧現異常則回滾操作,然後設置主動提交
                    conn.rollback();
                    conn.setAutoCommit(true);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

運轉成果:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved