天天看點

JDBC應用詳解

:::info

💡 概念:JDBC是java提供的一套用于操作資料庫的接口API:java程式員隻需要面向這套接口程式設計即可;

:::

java連接配接資料庫有五種方式:①靜态加載②使用反射動态加載

<a name="iS0E5"></a>

1 JDBC靜态加載,的使用步驟

<a name="FMxIe"></a>

1.1 注冊驅動【加載Driver類】

Driver driver = new Driver();
           

<a name="HQOk8"></a>

1.2 擷取連接配接【得到Connection】

Properties properties = new Properties();
String url = "jdbc:mysql://127.0.0.1:3306/school";
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);
           

<a name="ybjeV"></a>

1.3 執行增删改查【發送SQL指令】

String sql = "create table test";
        Statement statement = connect.createStatement();
        statement.executeUpdate(sql);
        
           

<a name="abnhG"></a>

1.4 釋放資源

connect.close();
        statement.close();
           

<a name="UKgZ0"></a>

2 反射動态加載資料庫

//    方式2 動态加載[使用反射加載driver類]
//        加載driver的Class對象
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) aClass.newInstance();
//        2得到連接配接
        String url = "jdbc:mysql://127.0.0.1:3306/school";
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "150896@zsl");
        Connection connect = driver.connect(url, properties);
//        3執行SQL
        String sql = "delete from person where id = 2";
//        建立statement對象
        Statement statement = connect.createStatement();
        int i = statement.executeUpdate(sql);
        System.out.println(i > 0 ? "成功" : "失敗!");
//        4關閉資源
        connect.close();
        statement.close();
           

<a name="NRfzd"></a>

3 使用DriverManager統一管理

//        方式3 使用DriverManager注冊驅動,進行統一管理
//        1 注冊驅動
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) aClass.newInstance();
        String url = "jdbc:mysql://localhost:3306/school";
        String user = "root";
        String password = "150896@zsl";
        DriverManager.registerDriver(driver);//注冊driver驅動
//        2擷取Connetion
        Connection connection = DriverManager.getConnection(url, user, password);
//        3 執行SQL操作
        String sql = "insert into person value (1,'韓順平',99,88,98)";
        Statement statement = connection.createStatement();
        int i = statement.executeUpdate(sql);
        System.out.println(i>0 ? "成功":"失敗");
//        3 關閉資源
        connection.close();
        statement.close();
           

<a name="rzoZj"></a>

<a name="HBE1g"></a>

4 推薦使用

//        方式4  使用Class.forName() 自動完成驅動,簡化代碼,
//        1 自動完成驅動注冊
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
//        建立url、user 、password
        String url = "jdbc:mysql://localhost:3306/school";
        String user = "root";
        String password = "150896@zsl";
//        2 建立連接配接
        Connection connection = DriverManager.getConnection(url, user, password);
//        3 執行SQL
        String sql = "insert into person value (2,'zsl',99,88,88)";
        Statement statement = connection.createStatement();
        int i = statement.executeUpdate(sql);
        System.out.println(i>0 ? "成功":"失敗");
//        4 關閉資源
        connection.close();
        statement.close();
           

<a name="dnI2z"></a>

5 ResultSet類的使用

<a name="hRN0a"></a>

5.1 基本介紹

(1)表示資料庫結果集的一個資料表,通常通過執行select語句生成<br />(2)ResultSet保持一個光标,指向目前資料行,最初光标位于第一行之前<br />(3)next方法将光标移到下一行,當在ResultSet對象沒有下一行對象時傳回false

//    ResultSet類的使用
        //        擷取配置檔案資訊
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
//       1 注冊驅動
        Class<?> aClass = Class.forName(driver);
        Driver driver1 = (Driver) aClass.newInstance();
//       2 建立連接配接
        Connection connection = DriverManager.getConnection(url, user, password);
//        3 執行SQL語句select語句
        String sql = "select * from person ";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            int Chinese = resultSet.getInt(3);
            System.out.println(id+"\t"+name+"\t"+Chinese);
        }
//        4 關閉資源
        connection.close();
        statement.close();
           

<a name="Q5xat"></a>

6 預處理PreparedStatement,與Statement相比更安全避免了SQL注入

// PreparedStatement預處理使用
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
//       1 注冊驅動
        Class<?> aClass = Class.forName(driver);
        Driver driver1 = (Driver) aClass.newInstance();
//       2 建立連接配接
        Connection connection = DriverManager.getConnection(url, user, password);
//        3 執行SQL語句select語句
        String na = "admin";
        String pw = "123";
//        SQL語句中的?相當與站位符
        String selectSql = "select id from user where `name` =? and pwd = ?";
        String addSql =  "insert into user value('001','admin','123')";
        String createTable = "create table  user ( id varchar(10),`name` varchar(10),pwd varchar(10))";
        PreparedStatement preparedStatement = connection.prepareStatement(selectSql);
        preparedStatement.setString(1,na);
        preparedStatement.setString(2,pw);
//        int i = preparedStatement.executeUpdate();
//        System.out.println(i>0? "成功":"失敗");
        ResultSet resultSet = preparedStatement.executeQuery();
        System.out.println(resultSet);
            while (resultSet.next()){
                String id = resultSet.getString(1);
                System.out.println(id);
            }
//        4 關閉資源
        connection.close();
      preparedStatement.close();
           

7 JDBC事務處理

8 JDBC的SQL語句批處理

public void batch(){
        Connection conection = JDBCUtils.getConection();
        String sql = "insert into admain value(?,?,?)";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conection.prepareStatement(sql);
            System.out.println("開始執行!");
            long starr = System.currentTimeMillis();
            for (int i = 0; i <= 1000; i++) {
                preparedStatement.setInt(1,i);
                preparedStatement.setString(2,"小明"+i);
                preparedStatement.setString(3,"123"+i);
//                将SQL語句加入批進行中
                preparedStatement.addBatch();
//                當有111條語句時批量執行
                if (i%100==0){//執行語句滿111
//                    批量執行
                    preparedStatement.executeBatch();
//                    清空
                    preparedStatement.clearBatch();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("批量處理執行時間:"+(end-starr));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JDBCUtils.getClose(preparedStatement,conection,null);

    }