Java封装JDBC数据库增、删、改、查操作成JAR文件,以供Web工程调用,适用于多种数据库

废话不多说,直接上源代码,最后有使用方法,当然,也可以作为普通公用类使用,只是封装成JAR更方便使用。

[java] view plain copy
 
  1. package db.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.sql.CallableStatement;    
  8. import java.sql.Connection;    
  9. import java.sql.DriverManager;    
  10. import java.sql.PreparedStatement;    
  11. import java.sql.ResultSet;    
  12. import java.sql.ResultSetMetaData;    
  13. import java.sql.SQLException;    
  14. import java.util.ArrayList;    
  15. import java.util.HashMap;    
  16. import java.util.List;    
  17. import java.util.Map;  
  18.   
  19. import org.json.JSONObject;  
  20.   
  21. /* 
  22.  * 说明:封装JDBC数据库增删改查、存储过程 
  23.  * 作者:Jiro.Chen 
  24.  * 时间:2016-12-12 15:13:54 
  25.  * */  
  26.   
  27. public class ConnectionUtil {  
  28.   
  29.     private static String DRIVER = null;    
  30.     
  31.     private static String URL = null;    
  32.     
  33.     private static String USERNAME = null;    
  34.     
  35.     private static String PASSWORD = null;    
  36.     
  37.     private Connection conn = null;    
  38.     
  39.     private PreparedStatement pstmt = null;    
  40.     
  41.     private CallableStatement callableStatement = null;    
  42.   
  43.     private ResultSet resultSet = null;    
  44.     
  45.     private void init(){  
  46.          try {     
  47.              Class.forName(DRIVER);    
  48.          } catch (ClassNotFoundException e) {    
  49.              System.out.println("加载驱动错误");  
  50.              System.out.println(e.getMessage());    
  51.          }  
  52.     }  
  53.       
  54.     public ConnectionUtil(String dbParam){  
  55.         String path = getCurrentPath();  
  56.         String filePath = path + "\db.JSON";  
  57.           
  58.         String text = null;  
  59.         try{  
  60.             text = this.readFile(new File(filePath));  
  61.             if(text.equals(null) || text.equals("")){  
  62.                 filePath = path + "\db.json";  
  63.                 text = this.readFile(new File(filePath));  
  64.                 if(text.equals(null) || text.equals("")){  
  65.                     System.out.println("找不到指定文件");  
  66.                 }  
  67.             }  
  68.         }catch(Exception e){  
  69.             e.printStackTrace();  
  70.         }  
  71.           
  72.         JSONObject json = new JSONObject(text);  
  73.         JSONObject DB = json.getJSONObject(dbParam);  
  74.           
  75.         DRIVER = DB.getString("DRIVER");  
  76.         URL = DB.getString("URL");  
  77.         USERNAME = DB.getString("USERNAME");  
  78.         PASSWORD = DB.getString("PASSWORD");  
  79.           
  80.         this.init();  
  81.     }  
  82.       
  83.     private String readFile(File file){  
  84.         String text = null;  
  85.           
  86.         try{  
  87.             if(file.isFile() && file.exists()){  
  88.                 InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");  
  89.                 BufferedReader bufferedReader = new BufferedReader(read);  
  90.                 String lineTxt = null;  
  91.                   
  92.                 while((lineTxt = bufferedReader.readLine()) != null){  
  93.                     text += lineTxt;  
  94.                 }  
  95.                 read.close();  
  96.             }  
  97.         }catch(Exception e){  
  98.             e.printStackTrace();  
  99.         }  
  100.           
  101.         return text;  
  102.     }  
  103.       
  104.     private String getCurrentPath(){  
  105.         String rootPath = null;  
  106.           
  107.         java.net.URL url = ConnectionUtil.class.getProtectionDomain().getCodeSource().getLocation();  
  108.         String filePath = null;  
  109.           
  110.         try{  
  111.             filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8");  
  112.         }catch (Exception e) {  
  113.             e.printStackTrace();  
  114.         }  
  115.           
  116.         if(filePath.endsWith(".jar")){  
  117.             filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);  
  118.         }  
  119.           
  120.         java.io.File file = new java.io.File(filePath);  
  121.         rootPath = file.getAbsolutePath();  
  122.           
  123.         rootPath = rootPath.substring(0, rootPath.lastIndexOf("\"));  
  124.         rootPath += "\classes";  
  125.           
  126.         return rootPath;  
  127.     }  
  128.       
  129.      
  130.     public Connection getConnection(){  
  131.         try{  
  132.             conn = DriverManager.getConnection(URL, USERNAME,    
  133.                     PASSWORD);  
  134.         }catch (SQLException e){    
  135.             System.out.println(e.getMessage());    
  136.         }  
  137.           
  138.         return conn;  
  139.     }  
  140.   
  141.     public int executeUpdate(String sql, Object[] params){  
  142.         int affectedLine = 0;  
  143.           
  144.         try{     
  145.             conn = this.getConnection();  
  146.      
  147.             pstmt = conn.prepareStatement(sql);    
  148.     
  149.             if (params != null){    
  150.                 for (int i = 0; i < params.length; i++){    
  151.                     pstmt.setObject(i + 1, params[i]);  
  152.                 }    
  153.             }  
  154.                  
  155.             affectedLine = pstmt.executeUpdate();    
  156.     
  157.         }catch (SQLException e){    
  158.             System.out.println(e.getMessage());    
  159.         }finally {     
  160.             closeAll();    
  161.         }  
  162.           
  163.         return affectedLine;    
  164.     }  
  165.     
  166.     /**  
  167.      * SQL 查询将查询结果直接放入ResultSet中 
  168.      */    
  169.     private ResultSet executeQueryRS(String sql, Object[] params){    
  170.         try{  
  171.             conn = this.getConnection();    
  172.                   
  173.             pstmt = conn.prepareStatement(sql);    
  174.                   
  175.             if (params != null){    
  176.                 for (int i = 0; i < params.length; i++){    
  177.                     pstmt.setObject(i + 1, params[i]);    
  178.                 }    
  179.             }  
  180.               
  181.             resultSet = pstmt.executeQuery();    
  182.     
  183.         }catch (SQLException e){    
  184.             System.out.println(e.getMessage());    
  185.         }  
  186.     
  187.         return resultSet;    
  188.     }    
  189.     
  190.     /**  
  191.      * 获取结果集,并将结果放在List中 
  192.      */    
  193.     public List<Object> excuteQuery(String sql, Object[] params){     
  194.         ResultSet rs = executeQueryRS(sql, params);    
  195.            
  196.         ResultSetMetaData rsmd = null;    
  197.            
  198.         int columnCount = 0;    
  199.         try{    
  200.             rsmd = rs.getMetaData();    
  201.                
  202.             columnCount = rsmd.getColumnCount();    
  203.         }catch (SQLException e1) {    
  204.             System.out.println(e1.getMessage());    
  205.         }    
  206.     
  207.         List<Object> list = new ArrayList<Object>();    
  208.     
  209.         try{      
  210.             while (rs.next()) {    
  211.                 Map<String, Object> map = new HashMap<String, Object>();    
  212.                 for (int i = 1; i <= columnCount; i++) {    
  213.                     map.put(rsmd.getColumnLabel(i), rs.getObject(i));    
  214.                 }    
  215.                 list.add(map);    
  216.             }    
  217.         }catch (SQLException e) {    
  218.             System.out.println(e.getMessage());    
  219.         }finally {     
  220.             closeAll();  
  221.         }  
  222.     
  223.         return list;    
  224.     }    
  225.         
  226.     /**  
  227.      * 存储过程带有一个输出参数的方法  
  228.      * @param sql 存储过程语句  
  229.      * @param params 参数数组  
  230.      * @param outParamPos 输出参数位置  
  231.      * @param SqlType 输出参数类型  
  232.      * @return 输出参数的值  
  233.      */    
  234.     public Object excuteQuery(String sql, Object[] params,int outParamPos, int SqlType){    
  235.         Object object = null;    
  236.         conn = this.getConnection();    
  237.           
  238.         try{     
  239.             callableStatement = conn.prepareCall(sql);    
  240.                
  241.             if(params != null){    
  242.                 for(int i = 0; i < params.length; i++) {    
  243.                     callableStatement.setObject(i + 1, params[i]);    
  244.                 }    
  245.             }    
  246.                
  247.             callableStatement.registerOutParameter(outParamPos, SqlType);    
  248.                 
  249.             callableStatement.execute();    
  250.                
  251.             object = callableStatement.getObject(outParamPos);    
  252.                 
  253.         }catch (SQLException e){    
  254.             System.out.println(e.getMessage());    
  255.         }finally{     
  256.             closeAll();  
  257.         }    
  258.             
  259.         return object;    
  260.     }    
  261.     
  262.     private void closeAll(){     
  263.         if (resultSet != null){    
  264.             try {    
  265.                 resultSet.close();    
  266.             } catch (SQLException e){    
  267.                 System.out.println(e.getMessage());    
  268.             }    
  269.         }    
  270.       
  271.         if(pstmt != null){    
  272.             try{    
  273.                 pstmt.close();    
  274.             } catch (SQLException e){    
  275.                 System.out.println(e.getMessage());    
  276.             }    
  277.         }    
  278.             
  279.         if(callableStatement != null){    
  280.             try{    
  281.                 callableStatement.close();    
  282.             }catch (SQLException e) {    
  283.                 System.out.println(e.getMessage());    
  284.             }    
  285.         }    
  286.      
  287.         if(conn != null){    
  288.             try{    
  289.                 conn.close();    
  290.             } catch (SQLException e) {    
  291.                 System.out.println(e.getMessage());    
  292.             }    
  293.         }       
  294.     }    
  295. }  


使用方法:

在Web工程src目录下新建db.JSON或者db.json文件

[plain] view plain copy
 
  1. {  
  2.     "DB":{  
  3.         "DRIVER"  :"com.microsoft.sqlserver.jdbc.SQLServerDriver",  
  4.         "URL"     :"jdbc:sqlserver://223.68.143.21:12922;DatabaseName=TwRailway_ECP",  
  5.         "USERNAME":"sa",  
  6.         "PASSWORD":"senao"  
  7.     }  
  8. }  

其中,DB可以有多个

工程导入JAR包之后,通过

[java] view plain copy
 
  1. ConnectionUtil conn = new ConnectionUtil("DB");  

配置文件db.JSON可以写多个数据库,参数DB指定使用哪种数据库建立连接

方法介绍:

1.public Connection getConnection()

  功能:

  JAR中提供了全套的增删改查的方法,但为了应对某种特殊情况下的需求,方法不能满足程序员需求时,可以使用此方法建立与数据库的连接,自行编写DAO层方法。

  参数说明:

  无

  传回值:

  传回Connection连接或NULL

2.public int executeUpdate(String sql, Object[] params)

  功能:

  使用PrepareStatement预处理执行sql,适用于数据新增、修改、删除等操作。

  参数说明:

  sql 执行的sql语句

  params 对象数组,存储要新增、修改或删除的数据。可以为空。

  传回值:

  传回1表示成功

  传回0表示失败

3.public List<Object> excuteQuery(String sql, Object[] params)

   功能:

   使用PrepareStatement预处理执行sql,适用于数据查询。

   参数说明:

   sql 执行的sql语句

   params 对象数组,sql语句中预设的值。可以为空。

   传回值:

   带有Map索引的List类型数据

只是适用于小型项目,减少DAO层编码量,增强代码的重用性。可以封装为公用类使用,也可以作为JAR档。

注意:此JAR依赖json.jar包。

原文地址:https://www.cnblogs.com/husam/p/7943743.html