1. 程式人生 > >11--Java--JDBC知識梳理

11--Java--JDBC知識梳理

JDBC

  一、概述:JDBC(java database connection),使用java語言連線資料庫,是java提供一套操作資料庫的介面(標準),實現對資料庫的統一訪問,是一個java引用應用程式與資料庫互動的橋樑。

              

 

    二、組成:

     DriverManager類:驅動管理類,使用者註冊驅動,獲取連線物件

       Connection介面:資料庫的連線物件

       Statement介面:執行SQL語句,操作資料

       PreparedStatement介面:執行SQL語句,操作資料

       ResultSet介面:接收SQL查詢結果(一張虛擬的表)    

      

 

    三、通過JDBC實現Query操作

      第一步:在資料庫中建立資料庫、新建表等一系列操作。

      第二步:在myeclipse中新建Web Project,建立與資料庫中資料表相對應的實體類 

      第三步:引入資料庫廠商提供的資料庫對應的驅動包(.jar格式...)到專案資料夾中的WebContent/WEB INF/lib/

      第四步:寫程式碼

       使用JDBC訪問資料庫的步驟:

          1.載入資料庫驅動(推薦方式二)

             import java.sql.DriverManager;

             方式一:DriverManager.registerDriver(new com.mysql.jdbc.Driver());//不推薦

             方式二:Class.forName("驅動類全稱:包名+類名"); //通過反射載入驅動,此處JDBC4.0後自動載入,可不用寫,但建議寫。

                 Class.forName("com.mysql.jdbc.Driver");

          2.獲取資料庫的連線物件(三種方式)

                import java.sql.Connection;

              Connection conn = DriverManager.getConnection("url","user","password");

                 url:1)統一資源定位符,標識網路上的一個具體資源(一個網頁,一張照片,一個視訊等)

                   2)url格式是 協議+ip地址+埠+資源名稱

                            jdbc:mysql :// localhost : 3306 / 資料庫名稱

                          jdbc:mysql :// 127.0.0.1 : 3306 / 資料庫名稱

                          jdbc:mysql :/// 資料庫名稱 (此種寫法預設本機)

                    user:資料庫使用者名稱

                   password:資料庫使用者密碼   

              Connection conn = DriverManager.getConnection("Path");//path等於url+user+password

                 path:jdbc:mysql://localhost:3306/資料庫名稱?user = ...&password = ...

              Connection conn = DriverManager.getConnection("url",properties);

                 properties:屬性物件

                 Properties p = new Properties();

                 p.setProperty("user","...");

                 p.setProperty("password","...");

               3.編寫SQL語句

                import java.sql.Statement;

                import java.sql.ResultSet;

              1)獲取SQL語句物件

                Statement st = conn.CreateStatement();

              2)執行SQL語句,返回結果

                ResultSet rs = st.executeQuery("select * from student");//執行查詢SQL語句,將查詢結果返回到結果集中

                String sql = "delete ....";

                int num = st.executeUpdate(sql);//執行更新(增刪改)SQL語句,返回的是int型的成功執行語句條數               

          4.處理結果集

              方式一:不建議使用

               while(rs.next()){//next()獲取的一張表的一行,也稱一條記錄

                 Object  id = rs.getObject(1);//獲取的是一張表的第一列,也稱一個欄位

                 Object  name = rs.getObject(2);//第二列

                 Object  age = rs.getObject(3);//第三列

               }

             方式二:方法中的引數名稱需要和資料表中的欄位名稱一致,並且建議建立資料庫中資料表的欄位時不要使用中文!!!

               while(rs.next()){//next()獲取的一張表的一行,也稱一條記錄

                     int id = rs.getInt("學號");//獲取的是一張表的第一列,也稱一個欄位

                     String name = rs.getString("姓名");//第二列

                  int  age = rs.getInt("年齡");//第三列

                 //如果資料庫中的Date型別,建議使用String接收

               }

          5.釋放連線資源。

             import java.sql.SQLException;

               finally{  //finally意思是在結尾無論前面發生了啥,程式總會執行這段程式碼

               if(conn != null){

                   try{ conn.close();

                 }catch(SQLException e){

                   e.printStackTrace();

                 }} 

                if(st != null){ 

                 try{ st.close();

                 }catch(SQLException e){

                   e.printStackTrace();

                 } }

               if(rs != null){ 

                 try{ rs.close();

                 }catch(SQLException e){

                   e.printStackTrace();

                 } }//所有物件通通關閉

              }

    四、注意:

     1.JDBC使用Statement會存在資料庫注入問題,因此需用PrepareStatement物件來解決

        String username = "1' or 1 = '1'";//設使用者名稱

            String password = "1' or 1 = '1'";//設密碼

        PrepareStatement pre = conn.prepareStatement("select * from student where username = ? and password = ?");//將SQL語句進行預處理,採用問號佔位符的形式

         pre.setString(1,username);//給第一個問號的位置賦值

         pre.setString(2,password);//給第二個問號的位置賦值

          ResultSet rs = pre.executeQuery();//執行賦值後的SQL語句

         

       五、封裝並呼叫JDBC工具類

      封裝工具類的程式碼:

 

 1 public class JDBCfunction{
 2       //靜態塊 優先執行,並且只執行一次
 3      static{
 4           try{
 5                //載入驅動
 6                Class.forName("com.mysql.jdbc.Driver");
 7            }catch(ClassNotFoundExcption e){
 8                 e.printStackTrack();
 9            }
10       }     
11       //連線物件
12       public static Connection getConnection(){
13             Connection conn = null;
14             try{
15                  conn = getConnection("jdbc:mysql://localhost:3306/databasename","username","password");
16             }catch(SQLExcption e){
17                  e.printStackTrack();
18            }
19            return conn;    
20       }
21       //釋放連線資源
22       public static void close(Connection conn,Statement st,ResultSet rs){
23             if(conn != null){
24                   try{
25                      conn.close();
26                   }catch(SQLExcption e){
27                       e.printStackTrack();
28                   }
29             }
30             if(st != null){
31                   try{
32                      st.close();
33                   }catch(SQLExcption e){
34                       e.printStackTrack();
35                   }
36             }
37             if(rs != null){
38                   try{
39                      rs.close();
40                   }catch(SQLExcption e){
41                       e.printStackTrack();
42                   }
43             }
44       }
45 }                      

 

                呼叫工具類的程式碼:(使用時需匯入Import JDBCfunction所在的檔案包)

 1 public class UseJDBCfunction(){
 2       public static void main(String[] args) throws SQLException{
 3             //載入驅動,建立連線
 4             Connection conn = JDBCfunction.getConnection();
 5             //建立預處理物件
 6             PrepareStatement pre = conn.prepareStatement("select * from student");
 7             //查詢
 8             ResultSet rs = pre.executeQuery();
 9             //遍歷輸出
10             while(rs.next()){ 
11                    int uid = rs.getInt("uid");
12                    String username = rs.getString("username");
13                    String password = rs.getString("password");
14                    User user = new User(uid,username,password);
15                    System.out.println(user);
16             }
17             //釋放資源
18             JDBCfunction.close(conn,pre,rs);
19       }  
20 }    

        六、JDBC批量操作

     1.jdbc設定事務自動提交,處理異常

        在連線物件conn與資料庫通過使用者名稱和密碼建立連線了之後,如果後續操作有catch異常,則不讓其conn物件最終對資料庫進行修改。

                             conn.setAutoCommit(false);//設定事務是否自動提交,預設為ture,自動提交。

                               conn.commit();//立即提交事務,對資料庫進行修改。

                               conn.rollback();//如果異常,事務回滾   

 1 public class UseJDBCfunction(){
 2         public static void main(String[] args) throws SQLException{
 3               Connection conn = null;
 4               PrepareStatement pre = null;
 5               try{ 
 6                   //載入驅動,建立連線
 7                   conn = JDBCfunction.getConnection();
 8                   conn.setAutoCommit(false);//禁止自動提交事務
 9                   //建立預處理物件
10                   pre = conn.prepareStatement("insert into user(username,password) value(?,?)");
11                   pre.setString(1,"xiaoming");
12                   pre.setString(2,"123");
13                   //更新
14                   int update = pre.executeUpdate();
15                   if(update > 0){
16                         System.out.println("新增成功");
17                         conn.commit();//提交事務
18                   }      
19              }catch(SQLException e){
20                     e.printTrackTrace();
21                     try{
22                          conn.rollback();//出現異常,事務回滾
23                      }catch(SQLException e){
24                          e.printTrackTrace();26                      }
27             }
28              //釋放資源
29              JDBCfunction.close(conn,pre,rs);
30        }  
31  }    

         2.jdbc批量新增

        在給預處理物件賦值時,採用pre.addBatch();的方式,對資料庫語句中的問號進行批量新增操作  

 1 public class UseJDBCfunction(){
 2         public static void main(String[] args) throws SQLException{
 3               Connection conn = null;
 4               PrepareStatement pre = null;
 5               try{ 
 6                   //載入驅動,建立連線
 7                   conn = JDBCfunction.getConnection();
 8                   conn.setAutoCommit(false);//禁止自動提交事務
 9                   //建立預處理物件
10                   pre = conn.prepareStatement("insert into user(username,password) value(?,?)");
11                   pre.addBatch();
12                   pre.setString(1,"m1");
13                   pre.setString(2,"123");
14                   
15                   pre.addBatch();
16                   pre.setString(1,"m2");
17                   pre.setString(2,"1234");
18 
19                   pre.addBatch();
20                   pre.setString(1,"m3");
21                   pre.setString(2,"12345");
22                   //......
23                    
24                   //更新(這是沒用批量操作的寫法)
25                   //int update = pre.executeUpdate();
26                   //更新(用批量操作的寫法,返回的是一個數組,因為資料庫添加了多條資料)
27                   int[]  executeBatch = pre.executebatch();
28                   if(executeBatch.length > 0){
29                         System.out.println("新增成功");
30                         conn.commit();//提交事務
31                   }      
32              }catch(SQLException e){
33                     e.printTrackTrace();
34                     try{
35                          conn.rollback();//出現異常,事務回滾
36                      }catch(SQLException e){
37                          e.printTrackTrace();26                      }
38             }
39              //釋放資源
40              JDBCfunction.close(conn,pre,rs);
41        }  
42  }         

&n