2020想學(xué)習(xí)JAVA的同學(xué)看過來,最基礎(chǔ)的編程CRUD你會了沒?

一 JDBC簡介

Java DataBase Connectivity Java語言連接數(shù)據(jù)庫

官方(Sun公司)定義的一套操作所有關(guān)系型數(shù)據(jù)庫的規(guī)則(接口) 各個數(shù)據(jù)庫廠商去實(shí)現(xiàn)這套接口 提供數(shù)據(jù)庫驅(qū)動JAR包 可以使用這套接口(JDBC)編程 真正執(zhí)行的代碼是驅(qū)動JAR包中的實(shí)現(xiàn)類

二 JDBC初體驗(yàn)

1. 新建一個Maven項(xiàng)目

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.hy.jdbc</groupId>
    <artifactId>jdbc-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 定義依賴版本號 -->
    <properties>
        <junit.version>4.12</junit.version>
        <mysql-connector-java.version>8.0.11</mysql-connector-java.version>
        <druid.version>1.1.10</druid.version>
    </properties>

    <!-- 管理jar版本號 -->
    <dependencyManagement>
        <dependencies>
            <!-- junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <!-- mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-connector-java.version}</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
    </dependencies>
</project>

sql

CREATE TABLE account (
    aid INT PRIMARY KEY,
    aname VARCHAR(100),
    amoney DOUBLE
);

2. 插入

@Test
public void test01() {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        // 注冊驅(qū)動 MySQL5之后的驅(qū)動JAR包可以省略該步驟
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取數(shù)據(jù)庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務(wù)
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "insert into account values(?, ?, ?)";
        // 獲取執(zhí)行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 設(shè)置參數(shù)
        statement.setInt(1, 1); //'?' 位置的編號 從1開始
        statement.setString(2, "No1"); //'?' 位置的編號 從1開始
        statement.setDouble(3, 2000); //'?' 位置的編號 從1開始
        // 執(zhí)行SQL 返回受影響的行數(shù)
        int count = statement.executeUpdate();
        // 提交事務(wù)
        connection.commit();
        // 處理結(jié)果
        System.out.println("count = " + count);

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務(wù)
        if (null != connection) {
            try {
                connection.rollback();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }

    } finally {
        // 釋放資源
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

3. 刪除

@Test
public void test02() {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        // 注冊驅(qū)動 MySQL5之后的驅(qū)動JAR包可以省略該步驟
        //Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取數(shù)據(jù)庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務(wù)
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "delete from account where aid = ?";
        // 獲取執(zhí)行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 設(shè)置參數(shù)
        statement.setInt(1, 1); //'?' 位置的編號 從1開始
        // 執(zhí)行SQL 返回受影響的行數(shù)
        int count = statement.executeUpdate();
        // 提交事務(wù)
        connection.commit();
        // 處理結(jié)果
        System.out.println("count = " + count);

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務(wù)
        if (null != connection) {
            try {
                connection.rollback();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }

    } finally {
        // 釋放資源
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

4. 修改

@Test
public void test03() {
    Connection connection = null;
    PreparedStatement statement1 = null;
    PreparedStatement statement2 = null;
    try {
        // 注冊驅(qū)動 MySQL5之后的驅(qū)動JAR包可以省略該步驟
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取數(shù)據(jù)庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務(wù)
        connection.setAutoCommit(false);
        // 定義SQL
        String sql1 = "update account set amoney = amoney + ? where aid = ?";
        String sql2 = "update account set amoney = amoney - ? where aid = ?";
        // 獲取執(zhí)行SQL的對象 PreparedStatement
        statement1 = connection.prepareStatement(sql1);
        statement2 = connection.prepareStatement(sql2);
        // 設(shè)置參數(shù)
        statement1.setDouble(1, 500); //'?' 位置的編號 從1開始
        statement1.setInt(2, 1); //'?' 位置的編號 從1開始
        statement2.setDouble(1, 500); //'?' 位置的編號 從1開始
        statement2.setInt(2, 2); //'?' 位置的編號 從1開始
        // 執(zhí)行SQL 返回受影響的行數(shù)
        statement1.executeUpdate();
        int i = 3 / 0; //模擬異常
        statement2.executeUpdate();
        // 提交事務(wù)
        connection.commit();

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務(wù)
        if (null != connection) {
            try {
                connection.rollback();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }

    } finally {
        // 釋放資源
        if (null != statement2) {
            try {
                statement2.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != statement1) {
            try {
                statement1.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

5. 查詢

@Test
public void test04() {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        // 注冊驅(qū)動 MySQL5之后的驅(qū)動JAR包可以省略該步驟
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取數(shù)據(jù)庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務(wù)
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "select * from account";
        // 獲取執(zhí)行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 執(zhí)行SQL 返回結(jié)果集
        resultSet = statement.executeQuery();
        // 提交事務(wù)
        connection.commit();
        // 處理結(jié)果
        while (resultSet.next()) {
            int id = resultSet.getInt(1); //代表列的編號 從1開始
            String name = resultSet.getString("aname"); //代表列的名稱
            double money = resultSet.getDouble(3); //代表列的編號 從1開始
            System.out.println(id + "---" + name + "---" + money);
        }

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務(wù)
        if (null != connection) {
            try {
                connection.rollback();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }

    } finally {
        // 釋放資源
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

三 數(shù)據(jù)庫連接池

一個存放數(shù)據(jù)庫連接的容器

當(dāng)系統(tǒng)初始化后 容器被創(chuàng)建 容器中會申請一些連接對象 當(dāng)用戶訪問數(shù)據(jù)庫時 從容器中獲取連接對象 用戶訪問完之后 會將連接對象歸還給容器 這樣可以節(jié)約資源 提高訪問效率

常見的數(shù)據(jù)庫連接池有 Druid C3P0...

Druid初體驗(yàn)

druid.properties

url=jdbc:mysql://localhost:3306/demo_hy
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=root
maxActive=10
minIdle=5

XTest.java

@Test
public void test05() {
    InputStream stream = null;
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        // 加載配置文件
        Properties properties = new Properties();
        stream = XTest.class.getClassLoader().getResourceAsStream("druid.properties");
        properties.load(stream);
        // 獲取連接池對象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        // 獲取數(shù)據(jù)庫連接對象 Connection
        connection = dataSource.getConnection();
        // 開啟事務(wù)
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "select * from account";
        // 獲取執(zhí)行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 執(zhí)行SQL 返回結(jié)果集
        resultSet = statement.executeQuery();
        // 提交事務(wù)
        connection.commit();
        // 處理結(jié)果
        while (resultSet.next()) {
            int id = resultSet.getInt(1); //代表列的編號 從1開始
            String name = resultSet.getString("aname"); //代表列的名稱
            double money = resultSet.getDouble(3); //代表列的編號 從1開始
            System.out.println(id + "---" + name + "---" + money);
        }

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務(wù)
        if (null != connection) {
            try {
                connection.rollback();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }

    } finally {
        // 釋放資源
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != connection) {
            try {
                connection.close(); //歸還連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != stream) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

最后

學(xué)習(xí)java不易,需要持續(xù)的堅(jiān)持,如果有想學(xué)習(xí)java的基礎(chǔ)知識或者進(jìn)階java的可以私信“學(xué)習(xí)”獲取學(xué)習(xí)聯(lián)系方式

file
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容