11--Java--JDBC知識梳理

JDBCjava

  1、概述:JDBC(java database connection),使用java語言鏈接數據庫,是java提供一套操做數據庫的接口(標準),實現對數據庫的統一訪問,是一個java引用應用程序與數據庫交互的橋樑。mysql

              

 

    2、組成:sql

     DriverManager類:驅動管理類,用戶註冊驅動,獲取鏈接對象數據庫

       Connection接口:數據庫的鏈接對象數組

       Statement接口:執行SQL語句,操做數據網絡

       PreparedStatement接口:執行SQL語句,操做數據eclipse

       ResultSet接口:接收SQL查詢結果(一張虛擬的表)    工具

      

 

    3、經過JDBC實現Query操做ui

      第一步:在數據庫中建立數據庫、新建表等一系列操做。url

      第二步:在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();

                 } }//全部對象統統關閉

              }

    4、注意:

     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語句

         

       5、封裝並調用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 }    

        6、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  }         

相關文章
相關標籤/搜索