1.加載驅動類
??????? Class.forName("com.mysql.jdbc.Driver")//針對mysql數據庫
2.創建數據庫連接
??????? DriverManager.getConnection(url,username,password);
??????? getConnection有不同參數方法,這里最常用的是我列舉的這種
??????????? url格式:
???????????????? MYSQL_URL:Jdbc::mysql://localhost:3306/qingke
???????????????? Oracle URL:Jdbc:oracle:thin:@localhost:1521:qingke
3.創建Statement
????????? Statement(靜態SQL):connection.createStatement();
????????? PreparedStatement(動態SQL):connection.prepareStatement();
????????? CallableStatement(數據庫存儲過程):connection.prepareCall();
4.執行SQL
????????? executeQuery:返回ResultSet(),執行查詢數據庫的SQL語句,返回一個結果集(ResultSet)對象
????????? executeUpdate:用于執行INSERT,UPDATE或DELETE語句以及SQL DDL語句,如CREATE TABLE和DROP TABLE
?????????? execute:用于執行返回多個結果集,多個更新計數或二者結合的語句。
5.處理結果
?????????? 執行更新返回的是本次操作影響到的記錄數
?????????? 執行查詢返回的是一個ResultSet對象
6.關閉JDBC
????????? 先關閉記錄集(ResultSet)
????????? 再關閉聲明(Statement)
????????? 最后關閉連接對象(Connection)
例子
public class Connect {
???????????? public static void main(String[]args){
???????????? Connection con=null;
???????????? Statement stmt=null;
???????????? ResultSet rs=null;
???? try {
???????????? Class.forName("com.mysql.jdbc.driver");
???????????? con=DriverManager.getConnection("jdbc:mysql://localhost:3306/iwanbesuper?useSSL=false", "username", "password");
???????????? stmt=con.createStatement();
???????????? rs=stmt.executeQuery("select * from student");
???????????? while(rs.next()){
??????????????????? System.out.println(rs.getString("name"));
???????????? }
???? } catch (ClassNotFoundException e) {
????????????? e.printStackTrace();
???? } catch (SQLException e) {
????????????? e.printStackTrace();
????? }finally{
//先關閉ResultSet
????? try {
????????????? if(rs!=null){
????????????? rs.close();
????? }
????? } catch (SQLException e) {
???????????? e.printStackTrace();
?????? }
?//再關閉Statement
???? try {
???????????? if(stmt!=null){
???????????? rs.close();
???? }
???? } catch (SQLException e) {
??????????? e.printStackTrace();
????? }
//最后關閉Connection
???? try {
???????????? if(con!=null){
???????????? rs.close();
? }
? } catch (SQLException e) {
e.printStackTrace();
}
}
}
}