天天看點

JDBC(mysql和Oracle兩種方法)中

作者:皮皮萌寶李時珍的皮

1.DriverManager

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.mysql.cj.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}           

注冊驅動,因為Driver可以直接注冊,是以代碼會先通過反射來獲得驅動

獲得資料庫的連接配接getConnection(String url,String user,String password)

url:連接配接路徑

user:使用者名

password:密碼

2.Connection

與特定資料庫的連接配接,獲得執行sql的對象

也可以對事務進行管理

try {
    //開啟事務
    connection.setAutoCommit(false);
    int count1= statement.executeUpdate(sql);
    int i = 3/0;
    int count2= statement.executeUpdate(sql2);
    //無錯誤送出事務
    connection.commit();
}catch (Exception e){
    // 復原事務
    connection.rollback();
    e.printStackTrace();
}           

setAutoCommit方法來開啟事務,參數設定為false

commit送出事務

rollback復原事務

3.Statement

來執行sql語句

executeUpdate執行DML和DDL語句

executeQuery執行查詢語句傳回值是int确定是影響的行數

public class Demo04 {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        Statement statement = connection.createStatement();
        String sql = "update users set password = 1 where username = 'admin'";
        int i = statement.executeUpdate(sql);
        System.out.println(i);
    }
}
           

也可以執行delete語句

4.PreparedStatement

預防SQL注入問題

import java.sql.*;

public class Demo05 {
    public static void main(String[] args)throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        String sql = "select * from users where username = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,"admin");
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()){
            String username = resultSet.getString("username");
            String pass = resultSet.getString("password");
            System.out.println(username+"--"+pass);

        }
    }
}           

和statement相似,後續的使用相同