Java JDBC(Java Database Connectivity)數據庫連接規範

1.四個核心類
DriverManager --創建連接
Connection --連接類
Statement --執行SQL語句
ResultSet --結果集
2.JDBC連接的六個步驟
1)註冊驅動
2)獲取連接-Connection
3)獲取sql語句的執行對象-Statement
4)執行sql語句,返回結果集-ResultSet
5)處理結果集
6)關閉資源
//查詢語句
public class Demo01 {
    public static void main(String[] args) throws Exception {
 //1.註冊驅動連接,用DriverManager類調用registerDriver(這裏填寫的是Driver匿名對象)方法,但是Driver裏面有一個靜態的代碼塊,當Driver這個類一加載就再次調用DriverManager.registerDriver(new com.mysql.jdbc.Driver());,所以不用這個了,直接將Driver類加載到內存中去,就可以了
 <!--DriverManager.registerDriver(new com.mysql.jdbc.Driver());-->
 //加載到內存中的格式:包名+類名
 Class.forName("com.mysql.jdbc.Driver");
//2.註冊完驅動,獲取連接對象
//這裏有三種獲取連接方式

//第一種
//url訪問數據的連接地址
String url = "jdbc:mysql://localhost:3306/數據庫名";
Connection connection = DriverManager.getConnection(url,"登錄名","登錄的密碼");

//第二種---我們需要創建Properties集合
Properties info = new Properties();
//設置鍵值對/屬性值
info.setProperty("user","root");//這裏是設置用戶名
info.setProperty("password","123456");//這裏是設置密碼的
Connection connection = DriverManager.getConnection(url,info);//這裏把集合中的數據都傳入獲取連接的方法裏

//第三種--使用get請求,攜帶參數,訪問連接
String url1 ="jdbc:mysql://localhost:3306/數據庫名?user=用戶名&password=密碼";
Connection connection = DriverManager.getConnection(null);

//3.獲取執行sql語句的對象
Statement statement = connection.createStatement();

//4.執行sql語句並返回結果集

//注:這裏結果集中所添加的索引,要和查詢語句中的字段相對應

//這裏是查詢語句
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);


//5.處理結果集,

while(resultSex.next()){
    System.out.println(resultSet.getObject(1));
         System.out.println(resultSet.getObject(2));
         System.out.println(resultSet.getObject(3));
         System.out.println(resultSet.getObject(4));
         System.out.println(resultSet.getObject(5));
         System.out.println("_____________________"); 
}

//6.關閉資源
resultSet.close();
statement.close();
connection.close();
//增刪改查語句

public class DemoCRUD{
//註解:用來測試方法
    @Test 
  public void test throws Exception{
      Class.forName("com.mysql.jdbc.Driver");
      String url = "jdbc:mysql://localhost:3306/myjdbc"

   Connection connection = DriverManager.getConnection(url,"root","123455");
   Statement statement = connection.createStatement();

  //這裏是添加數據
   String  sql ="insert into users values(2,'gs','123','[email protected]','1993-1-1')";

  //statement.executeUpdate();sql執行對象調用更新方法,這個方式也是刪除的方法



  int  row = statement.executeUpdate(sql);
 //這裏返回的row表示受影響的行數
 //我們可以通過受影響行數來判斷是否執行成功
 if(row>0){
     System.out.println("插入成功");
 }
  }
}
//連接數據庫連接異常處理
//這裏我們把結果集的每條記錄當做對象放到集合當中,所以我們先創建一個對象,將一條記錄的每一列添加到對象中

//創建一個User對象
public class User {
 //我們設置是,對於對象中的屬性名,儘量和數據庫中的字段名相同,不容易出錯
    private int id;
    private String name;
    private String password;
    private String email;
    private Date birthday;

    public User() {
        super();
    }

    public User(int id, String name, String password, String email, Date birthday) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
        this.email = email;
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User[id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", birthday="
                + birthday + "]";
    }

}


public class DemoException {
 public static void main(String[] args) {
 Connection connection = null;
 Statement statement = null;
 ResultSet resultSet = null;
 try{
     //這裏會有加載驅動失敗異常
     Class.forName("com.mysql.jdbc.Driver");
    //這裏是連接數據庫異常
    String url = "jdbc:mysql://localhos:3306/myjdbc";
    connection = DriverManager.getConnection(url,"root","123456");
    statement = connection.createStatement();
    String sql = "select * from users";
    resultSet = statement.executeQuery(sql);
  //創建一個集合,用於存儲每條記錄的當做一個對象的集合
  ArrayList<User> list = new ArrayList<>();
  while(resultSet.next()){
     //這裏我們創建User對象,並通過結果集對象調用獲取方法對應的給對象的變量賦值
     User user = new User();
     user.setId(resultSet.getInt("id"));
     user.setName(resultSet.getString("name"));
     user.setPassword(resultSet.getString("password"));
     user.setEmail(resultSet.getString("email"));
     user.setBirthday(resultSet.getDate("birthday"));
    //賦值完畢,添加到集合中
    list.add(user);

  }
  //遍歷打印集合中的對象數據
  for(User user :list){
      System.out.println(user);

  }
 } catch (SQLException e) {
         e.printStackTrace();
            throw new RuntimeException("獲取連接失敗");
        }
     catch (ClassNotFoundException e) {
         e.printStackTrace();
        throw new RuntimeException("驅動加載失敗");
    }finally {

    }

}
}
//這裏將,獲取數據庫的連接方法,連接數據庫異常,建立工具類便於調用
//首先,我們要先創建一個配置文件
//1.在src下創建一個文本文件,這裏起名一般保存的後綴名是.properties,dbinfo.properties(文本名)
//2.數據是:
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myjdbc
user=root
password=123456


public class JDBCUtil {
 private static String driverClass;
 private static String url;
 private static String user;
 private static String password;
 //第一種,先使用集合讀取文件
 Properties properties = new Properties();
 try{
     FileInputStream fis = new FileInputStream("src/dbinfo.propeerties");//注:這裏後綴要寫全
     properties.load(fis);
    //根據鍵讀取對應的值
    driverClass = properties,getProperty("driverClass");
    url = properties.getProperty("url");
    user = properties.getProperty("user");
    password = properties.getProperty("password");
    }catech (Exception e) {
            e.printStackTrace();
        }
//第二種,使用系統類來讀取配置文件
//我們在靜態代碼塊裏編寫讀取配置文件
ResourceBundle rb = ResourceBundle.getBundle("dbinfo");//注:這裏的後綴不寫
//獲取文件中的數據
driverClass = rb.getString("driverClass");
url = rb.getString("url");
user = rb.getString("user");
password = rb.getString("password");

//這裏加載驅動,靜態代碼塊只加載一次
try {
             //驅動加載失敗異常
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
//獲取數據庫連接的方法
public static Connection getConnection() throws SQLException {
   return DriverManager.getConnection(url,user,password);
   }
  //關閉數據庫的方法
 public static void closeAll(ResultSet resultSet,Statement statement,Connection connection){
    //這裏關閉資源前,要先做非空判斷才能確定關閉資源否
    if(resultSet != null){
        try{
            resultSet.close();
        }catch (SQLException e){
            throw new RuntimeException("關閉失敗");
        }
        resultSet = null;//這裏是將結果集清空,加快系統回收速度
    }if(connection != null) {
                try {
                    connection.close();

                } catch (SQLException e) {
                    throw new RuntimeException("關閉失敗");
                }
                connection = null;
            }
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException("關閉失敗");
                }
        //這裏清空數據處理對象,便於加快系統垃圾回收
                statement = null;
            }   
     }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章