2020想學習JAVA的同學看過來,最基礎的編程CRUD你會了沒?

来源:https://www.cnblogs.com/MonsterJ/archive/2020/07/26/13381853.html
-Advertisement-
Play Games

一 JDBC簡介 Java DataBase Connectivity Java語言連接資料庫 官方(Sun公司)定義的一套操作所有關係型資料庫的規則(介面) 各個資料庫廠商去實現這套介面 提供資料庫驅動JAR包 可以使用這套介面(JDBC)編程 真正執行的代碼是驅動JAR包中的實現類 二 JDBC ...


一 JDBC簡介

Java DataBase Connectivity Java語言連接資料庫

官方(Sun公司)定義的一套操作所有關係型資料庫的規則(介面) 各個資料庫廠商去實現這套介面 提供資料庫驅動JAR包 可以使用這套介面(JDBC)編程 真正執行的代碼是驅動JAR包中的實現類

二 JDBC初體驗

1. 新建一個Maven項目

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 {
        // 註冊驅動 MySQL5之後的驅動JAR包可以省略該步驟
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取資料庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "insert into account values(?, ?, ?)";
        // 獲取執行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 設置參數
        statement.setInt(1, 1); //'?' 位置的編號 從1開始
        statement.setString(2, "No1"); //'?' 位置的編號 從1開始
        statement.setDouble(3, 2000); //'?' 位置的編號 從1開始
        // 執行SQL 返回受影響的行數
        int count = statement.executeUpdate();
        // 提交事務
        connection.commit();
        // 處理結果
        System.out.println("count = " + count);

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務
        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 {
        // 註冊驅動 MySQL5之後的驅動JAR包可以省略該步驟
        //Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取資料庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "delete from account where aid = ?";
        // 獲取執行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 設置參數
        statement.setInt(1, 1); //'?' 位置的編號 從1開始
        // 執行SQL 返回受影響的行數
        int count = statement.executeUpdate();
        // 提交事務
        connection.commit();
        // 處理結果
        System.out.println("count = " + count);

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務
        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 {
        // 註冊驅動 MySQL5之後的驅動JAR包可以省略該步驟
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取資料庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務
        connection.setAutoCommit(false);
        // 定義SQL
        String sql1 = "update account set amoney = amoney + ? where aid = ?";
        String sql2 = "update account set amoney = amoney - ? where aid = ?";
        // 獲取執行SQL的對象 PreparedStatement
        statement1 = connection.prepareStatement(sql1);
        statement2 = connection.prepareStatement(sql2);
        // 設置參數
        statement1.setDouble(1, 500); //'?' 位置的編號 從1開始
        statement1.setInt(2, 1); //'?' 位置的編號 從1開始
        statement2.setDouble(1, 500); //'?' 位置的編號 從1開始
        statement2.setInt(2, 2); //'?' 位置的編號 從1開始
        // 執行SQL 返回受影響的行數
        statement1.executeUpdate();
        int i = 3 / 0; //模擬異常
        statement2.executeUpdate();
        // 提交事務
        connection.commit();

    } catch (Exception e) {
        e.printStackTrace();
        // 回滾事務
        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 {
        // 註冊驅動 MySQL5之後的驅動JAR包可以省略該步驟
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 獲取資料庫連接對象 Connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo_hy", "root", "root");
        // 開啟事務
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "select * from account";
        // 獲取執行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 執行SQL 返回結果集
        resultSet = statement.executeQuery();
        // 提交事務
        connection.commit();
        // 處理結果
        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();
        // 回滾事務
        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();
            }
        }
    }
}

三 資料庫連接池

一個存放資料庫連接的容器

當系統初始化後 容器被創建 容器中會申請一些連接對象 當用戶訪問資料庫時 從容器中獲取連接對象 用戶訪問完之後 會將連接對象歸還給容器 這樣可以節約資源 提高訪問效率

常見的資料庫連接池有 Druid C3P0...

Druid初體驗

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);
        // 獲取資料庫連接對象 Connection
        connection = dataSource.getConnection();
        // 開啟事務
        connection.setAutoCommit(false);
        // 定義SQL
        String sql = "select * from account";
        // 獲取執行SQL的對象 PreparedStatement
        statement = connection.prepareStatement(sql);
        // 執行SQL 返回結果集
        resultSet = statement.executeQuery();
        // 提交事務
        connection.commit();
        // 處理結果
        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();
        // 回滾事務
        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();
            }
        }
    }
}

最後

學習java不易,需要持續的堅持,如果有想學習java的基礎知識或者進階java的可以私信“學習”獲取學習聯繫方式

file


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、PreparedStatement介面 1.java.sql.PraparedStatement介面繼承並擴展了Statement介面,用於執行動態的SQL語句,即包含參數的SQL語句。 PraparedStatement ps = connection.preparedStatement("s ...
  • IO讀寫基礎 應用層在進行read,write系統調用時,不是物理級別的讀寫,而是緩存的複製,進程緩衝區同內核緩衝區的緩存複製,底層數據交換是有由操作系統內核完成,控制內核緩衝與硬體(物理設備)之間數據交換.linux系統在系統內核只有一個內核緩衝區,用戶進程都有獨立的緩衝區,是進程緩衝區。外部設備 ...
  • 內置異常和Throwable核心方法 Java內置異常 可查異常(必須要在方法裡面捕獲或者拋出) ClassNoFoundException 應⽤程式試圖載入類,找不到對應的類 IllegalAccessException 拒絕訪問⼀個類的時候 NoSuchFieldExcetion 請求的變數不存 ...
  • VSCode配置Rust開發環境 在商店中輸入rls,選擇rust,點擊Quick start中的下載鏈接。這個Rust插件你也要記得下。 跳轉後來到下載界面,點擊下載。 運行下載好的exe文件,命令行輸入1按下回車即可。 安裝完畢後在命令行輸入rustc --version,如果能輸出版本號則表示 ...
  • 一、Tomcat的安裝及簡單使用 在網上找到你需要安裝的Tomcat版本,解壓到你需要安裝的目錄就可以了 目錄介紹: bin 專門用來存放 Tomcat 伺服器的可執行程式 conf 專門用來存放 Tocmat 伺服器的配置文件 lib 專門用來存放 Tomcat 伺服器的 jar 包 logs 專 ...
  • Java是啥 新手程式員通常會走入一個誤區,就是認為學習了一門語言,就可以稱為是某某語言工程師了。但事實上真的是這樣嗎?其實並非如此。 今天我們就來聊一聊,Java 開發工程師到底開發的是什麼東西。準確點來說,Java後端到底在做什麼? 基礎 大家都知道 Java 是一門後端語言,後端指的就是服務端 ...
  • 最近有很多小伙伴來問我,Java小白如何入門,如何安排學習路線,每一步應該怎麼走比較好。原本我以為之前的幾篇文章已經可以解決大家的問題了,其實不然,因為我之前寫的文章都是站在Java後端的全局上進行思考和總結的,忽略了很多小白們的感受,而很多朋友都需要更加基礎,更加詳細的學習路線。 所以,今天我們重 ...
  • 秋招總結 寫在最前 我寫過很多篇秋招總結,這篇文章應該是最後一篇總結,當然也是最完整,最詳細的一篇總結。秋招是我人生中一段寶貴的經歷,不僅是我研究生生涯交出的一份答卷,也是未來職業生涯的開端。僅以此文,獻給自己,以及各位在求職路上的,或者是已經經歷過校招的朋友們。不忘初心,方得始終。 前言 在下本是 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:本文代碼示例演示瞭如何在WPF中使用LiveCharts庫創建動態條形圖。通過創建數據模型、ViewModel和在XAML中使用`CartesianChart`控制項,你可以輕鬆實現圖表的數據綁定和動態更新。我將通過清晰的步驟指南包括詳細的中文註釋,幫助你快速理解並應用這一功能。 先上效果: 在 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • 概述:本示例演示了在WPF應用程式中實現多語言支持的詳細步驟。通過資源字典和數據綁定,以及使用語言管理器類,應用程式能夠在運行時動態切換語言。這種方法使得多語言支持更加靈活,便於維護,同時提供清晰的代碼結構。 在WPF中實現多語言的一種常見方法是使用資源字典和數據綁定。以下是一個詳細的步驟和示例源代 ...
  • 描述(做一個簡單的記錄): 事件(event)的本質是一個委托;(聲明一個事件: public event TestDelegate eventTest;) 委托(delegate)可以理解為一個符合某種簽名的方法類型;比如:TestDelegate委托的返回數據類型為string,參數為 int和 ...
  • 1、AOT適合場景 Aot適合工具類型的項目使用,優點禁止反編 ,第一次啟動快,業務型項目或者反射多的項目不適合用AOT AOT更新記錄: 實實在在經過實踐的AOT ORM 5.1.4.117 +支持AOT 5.1.4.123 +支持CodeFirst和非同步方法 5.1.4.129-preview1 ...
  • 總說周知,UWP 是運行在沙盒裡面的,所有許可權都有嚴格限制,和沙盒外交互也需要特殊的通道,所以從根本杜絕了 UWP 毒瘤的存在。但是實際上 UWP 只是一個應用模型,本身是沒有什麼許可權管理的,許可權管理全靠 App Container 沙盒控制,如果我們脫離了這個沙盒,UWP 就會放飛自我了。那麼有沒... ...
  • 目錄條款17:讓介面容易被正確使用,不易被誤用(Make interfaces easy to use correctly and hard to use incorrectly)限制類型和值規定能做和不能做的事提供行為一致的介面條款19:設計class猶如設計type(Treat class de ...
  • title: 從零開始:Django項目的創建與配置指南 date: 2024/5/2 18:29:33 updated: 2024/5/2 18:29:33 categories: 後端開發 tags: Django WebDev Python ORM Security Deployment Op ...
  • 1、BOM對象 BOM:Broswer object model,即瀏覽器提供我們開發者在javascript用於操作瀏覽器的對象。 1.1、window對象 視窗方法 // BOM Browser object model 瀏覽器對象模型 // js中最大的一個對象.整個瀏覽器視窗出現的所有東西都 ...