国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

jdbc一般步驟

2019-11-14 11:01:13
字體:
來源:轉載
供稿:網友

java 原生JDBC操作數據庫,是比較常見的面試題,所以一定要牢牢掌握住。

記住一般步驟,就好寫代碼了。

1、Class.forName()加載數據庫連接驅動。

2、DriverManager.getConnection()獲取數據連接對象。

3、根據SQL語句獲取會話對象,會話對象一般用PReparedStatement類型,conn.prepareStatement(),注意方法名和類名不一樣喲。

4、執行SQL處理結果集,執行SQL前如果有參數值就設置參數值setXXX()。

5、關閉結果集、關閉會話、關閉連接。

[java] view plain copy 在CODE上查看代碼片package com.lcx.test;    import java.sql.Connection;  import java.sql.DriverManager;  import java.sql.PreparedStatement;  import java.sql.ResultSet;  import java.sql.SQLException;  import java.sql.Savepoint;  import java.util.Properties;    public class Test {      public static void main(String[] args) {          String url1="jdbc:MySQL://localhost:3306/JAVA?user=root&passWord=root&useUnicode=true&charactorEncoding=UTF8";          String url2="jdbc:mysql://localhost:3306/JAVA?useUnicode=true&charactorEncoding=UTF8";          String url3="jdbc:mysql://localhost:3306/JAVA";          String user="root";          String password="root";          Connection conn3 = null;          Savepoint point1 = null;                    try {              //1、加載數據庫驅動,包名一般為域名反寫              Class.forName("com.mysql.jdbc.Driver");              Properties info = new Properties();              info.put("user", "root");              info.put("password", "root");              info.put("useUnicode","true");              info.put("charactorEncoding","utf8");              /*              * 2、獲取數據連接對象,DriverManager.getConnection方法有3個重載方法              */  //          Connection conn1 = DriverManager.getConnection(url3, user, password);//將連接的用戶名、密碼放到方法參數中  //          Connection conn2 = DriverManager.getConnection(url2,info);//將連接的屬性鍵值對放在Properties對象中              conn3 = DriverManager.getConnection(url1);//將所有連接信息都放在URL中              /*              * 3、根據SQL獲取sql會話對象,有2種方式 Statement、PreparedStatement              *      1、 PreparedStatement接口繼承Statement, PreparedStatement 實例包含已編譯的 SQL 語句,所以其執行速度要快于 Statement 對象。              *      2、作為 Statement 的子類,PreparedStatement 繼承了 Statement 的所有功能。三種方法  execute、 executeQuery 和 executeUpdate 已被更改以使之不再需要參數              *      3、在JDBC應用中,如果你已經是稍有水平開發者,你就應該始終以PreparedStatement代替 Statement.也就是說,在任何時候都不要使用Statement.              *          一.代碼的可讀性和可維護性.Statement需要不斷地拼接,而PreparedStatement不會。              *          二.PreparedStatement盡最大可能提高性能.DB有緩存機制,相同的預編譯語句再次被調用不會再次需要編譯。              *          三.最重要的一點是極大地提高了安全性.Statement容易被SQL注入,而PreparedStatementc傳入的內容不會和sql語句發生任何匹配關系。              * 最常用的api              * addBatch()/addBatch(String sql) 預編譯SQL語句,只編譯一回哦,效率高啊。剝瓜子,一個一個剝,最后一口吃。              * setXXX(parameterIndex,value) 設置指定參數的值。              * execute()  執行 SQL 語句,該語句可以是任何種類的 SQL 語句。              * executeQuery() 執行查詢語句返回ResultSet              * executeUpdate() 執行增刪改,返回影響的行數。              *               */              String sql_other = "TRUNCATE TABLE t_user_info";              String sql_insert = "insert into t_user_info(id,user,sex,age) value(null,?,?,?)";              String sql_query = "select * from t_user_info where id < ?";              conn3.setAutoCommit(false);//關閉自動提交              PreparedStatement preparedStatement_other = conn3.prepareStatement(sql_other);              PreparedStatement preparedStatement_insert = conn3.prepareStatement(sql_insert);              PreparedStatement preparedStatement_query = conn3.prepareStatement(sql_query);              preparedStatement_other.execute();                                          for(int i=0;i<100;i++){                  preparedStatement_insert.setString(1, "user_"+i);                  preparedStatement_insert.setString(2, "n");                  preparedStatement_insert.setInt(3, i);                  if(i>50){  //                  preparedStatement_insert.setString(3, "我是錯誤的嘗試");                  }                  preparedStatement_insert.addBatch();              }              //一次性插入100條記錄,如果中間有出錯,那么這一次性的插入都不會成功              int[] updateInt = preparedStatement_insert.executeBatch();              conn3.commit();              point1 = conn3.setSavepoint("point1");              System.out.println(updateInt.length);                            preparedStatement_query.setInt(1, 50);              //4、執行SQL語句,查詢語句就獲取結果集              ResultSet result = preparedStatement_query.executeQuery();              while(result.next()){                  int a = result.getInt("id");                  int b = result.getInt(1);                  System.out.println("第一列值,通過列名:"+a+",通過下標:"+b);                                }              /*              * 5、關閉結果集、關閉會話、關閉連接              */              result.close();              preparedStatement_other.close();              preparedStatement_insert.close();              preparedStatement_query.close();              conn3.close();                        } catch (ClassNotFoundException e) {              System.out.println("驅動沒有加載到。。。");              e.printStackTrace();          } catch (SQLException e) {              System.out.println("出現sql異常。。。");              try {                  conn3.rollback(point1);;              } catch (SQLException e1) {                                    e1.printStackTrace();              }              e.printStackTrace();          }      }  }  JDBC%20進一步封裝

我們將獲取連接和釋放連接封裝到工具類中,執行SQL的感覺沒有必要封裝,這樣更靈活。

[java] view%20plain copy package com.lcx.test;    import java.sql.Connection;  import java.sql.DriverManager;  import java.sql.ResultSet;  import java.sql.SQLException;  import java.sql.Statement;    public class JDBCUtil {      /**      * jdbc:mysql://主機名稱:連接端口/數據庫的名稱?參數=值      * String url = "jdbc:mysql://localhost:3306/JAVA?user=root&password=root&useUnicode=true&characterEncoding=UTF8";      * 也可在獲取連接的時候使用用戶名和密碼      * 避免中文亂碼要指定useUnicode和characterEncoding, 執行數據庫操作之前要在數據庫管理系統上創建一個數據庫,名字自己定,      */      private static final String url="jdbc:mysql://localhost:3306/JAVA";      private static final String user="root";      private static final String password="root";      private static Connection conn;      //靜態代碼塊,類加載時就加載驅動      static {          //1、加載驅動          try {              Class.forName("com.mysql.jdbc.Driver");          } catch (ClassNotFoundException e) {              System.out.println("Exception: com.mysql.jdbc.driver not found Exception");              e.printStackTrace();          }      }      private JDBCUtil(){                }      //2獲取連接的方法,只產生一個連接      public static Connection getConnection(){          try {              if(conn==null){                  synchronized (JDBCUtil.class) {                      if(conn==null){                          conn = DriverManager.getConnection(url, user, password);                      }                  }              }          } catch (SQLException e) {              System.out.println("Exception: get mysql connection Exception");              e.printStackTrace();          }          return conn;      }      //最后釋放資源,中間操作由preparedStatement 去操作更靈活      public static void free(ResultSet result,Statement statement,Connection connection){          try {              if(result!=null){//關閉結果集                  result.close();              }          } catch (SQLException e) {              e.printStackTrace();          }finally{              try {                  if(statement!=null){//關閉statement會話                      statement.close();                  }              } catch (SQLException e) {                  e.printStackTrace();              }finally{                  try {                      if(connection!=null){                          connection.close();//關閉連接                      }                  } catch (SQLException e) {                      e.printStackTrace();                  }              }                        }                }  }  使用工具類操作數據處理

[java] view%20plain copy 派生到我的代碼片package com.lcx.test;    import java.sql.Connection;  import java.sql.PreparedStatement;  import java.sql.ResultSet;  import java.sql.SQLException;    public class JDBCTest {        public static void main(String[] args) {          //1、加載驅動、獲取連接          Connection connection = JDBCUtil.getConnection();          String sql_init ="TRUNCATE TABLE t_user_info";          String sql_insert = "insert into t_user_info(id,user,sex,age) value(null,?,?,?)";          String sql_query = "select * from t_user_info where id < ?";          PreparedStatement ps_init;          PreparedStatement ps_insert;          PreparedStatement ps_query;          try {              connection.setAutoCommit(false);              //2、根據sql語句獲取 獲取預編譯語句對象              ps_init = connection.prepareStatement(sql_init);              ps_insert = connection.prepareStatement(sql_insert);              ps_query = connection.prepareStatement(sql_query);                            ps_init.execute();//可以執行任何種類的SQL語句              //3、有參數值,就設置參數值,然后執行預編譯語句,獲取結果集              for(int i=0;i<100;i++){                  ps_insert.setString(1, "user_"+i);                  ps_insert.setString(2, "n");                  ps_insert.setInt(3, i);                  ps_insert.addBatch();//增加的批處理隊列中              }              ps_insert.executeBatch();//一次性執行                            ps_query.setInt(1, 50);              //查詢記錄,獲取結果集              ResultSet result = ps_query.executeQuery();              while(result.next()){                  int a = result.getInt("id");                  int b = result.getInt(1);                  System.out.println("第一列通過列明:"+a+",第一列通過index:"+b);              }              connection.commit();              //5、釋放資源              JDBCUtil.free(result, ps_query, connection);              JDBCUtil.free(result, ps_init, connection);              JDBCUtil.free(result, ps_insert, connection);          } catch (SQLException e) {              try {                  connection.rollback();              } catch (SQLException e1) {                  e1.printStackTrace();              }              e.printStackTrace();          }                }    }  
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 高安市| 江北区| 伊宁市| 会东县| 富源县| 彩票| 正宁县| 襄城县| 高阳县| 竹溪县| 光泽县| 桃源县| 怀仁县| 城固县| 孟连| 吉安市| 呼和浩特市| 资溪县| 马鞍山市| 油尖旺区| 天峨县| 绥江县| 得荣县| 观塘区| 铅山县| 东光县| 鞍山市| 抚州市| 长顺县| 会东县| 新丰县| 铜鼓县| 新巴尔虎左旗| 江达县| 温宿县| 襄城县| 逊克县| 莱西市| 县级市| 莲花县| 荆州市|