1.加載驅動類
??????? Class.forName("com.mysql.jdbc.Driver")//針對mysql數(shù)據(jù)庫
2.創(chuàng)建數(shù)據(jù)庫連接
??????? DriverManager.getConnection(url,username,password);
??????? getConnection有不同參數(shù)方法,這里最常用的是我列舉的這種
??????????? url格式:
???????????????? MYSQL_URL:Jdbc::mysql://localhost:3306/qingke
???????????????? Oracle URL:Jdbc:oracle:thin:@localhost:1521:qingke
3.創(chuàng)建Statement
????????? Statement(靜態(tài)SQL):connection.createStatement();
????????? PreparedStatement(動態(tài)SQL):connection.prepareStatement();
????????? CallableStatement(數(shù)據(jù)庫存儲過程):connection.prepareCall();
4.執(zhí)行SQL
????????? executeQuery:返回ResultSet(),執(zhí)行查詢數(shù)據(jù)庫的SQL語句,返回一個結果集(ResultSet)對象
????????? executeUpdate:用于執(zhí)行INSERT,UPDATE或DELETE語句以及SQL DDL語句,如CREATE TABLE和DROP TABLE
?????????? execute:用于執(zhí)行返回多個結果集,多個更新計數(shù)或二者結合的語句。
5.處理結果
?????????? 執(zhí)行更新返回的是本次操作影響到的記錄數(shù)
?????????? 執(zhí)行查詢返回的是一個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();
}
}
}
}