9.JDBC

哈士费發表於2024-05-08

什麼是JDBC:java連線資料庫!

新增jar包

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
    </dependencies>

外部庫

小小的測試

public class TestJdbc {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        // 配置資訊
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        // 1.載入驅動
        Class.forName("com.mysql.jdbc.Driver");
        // 2.連線資料庫 代表資料庫
        Connection connection = DriverManager.getConnection(url, username, password);
        // 3.向資料庫傳送SQL的物件Statement :CRUD
        Statement statement = connection.createStatement();
        // 4.編寫SQL
        String sql = "select * from users";
        // 5.執行sql 返回結果
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("name"));
            System.out.println("password="+resultSet.getObject("password"));
            System.out.println("email="+resultSet.getObject("email"));
            System.out.println("birthday="+resultSet.getObject("birthday"));
        }

        // 6.關閉連線,釋放資源
        resultSet.close();
        statement.close();
        connection.close();
    }
}