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

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

package db.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.CallableStatement;  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.ResultSetMetaData;  
import java.sql.SQLException;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;

import org.json.JSONObject;

/*
 * 说明:封装JDBC数据库增删改查、存储过程
 * 作者:Jiro.Chen
 * 时间:2016-12-12 15:13:54
 * */

public class ConnectionUtil {

    private static String DRIVER = null;  
  
    private static String URL = null;  
  
    private static String USERNAME = null;  
  
    private static String PASSWORD = null;  
  
    private Connection conn = null;  
  
    private PreparedStatement pstmt = null;  
  
    private CallableStatement callableStatement = null;  

    private ResultSet resultSet = null;  
  
    private void init(){
    	 try {   
             Class.forName(DRIVER);  
         } catch (ClassNotFoundException e) {  
             System.out.println("加载驱动错误");
             System.out.println(e.getMessage());  
         }
    }
    
    public ConnectionUtil(String dbParam){
    	String path = getCurrentPath();
    	String filePath = path + "\\db.JSON";
    	
    	String text = null;
    	try{
    		text = this.readFile(new File(filePath));
    		if(text.equals(null) || text.equals("")){
    			filePath = path + "\\db.json";
    			text = this.readFile(new File(filePath));
    			if(text.equals(null) || text.equals("")){
    				System.out.println("找不到指定文件");
    			}
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	
    	JSONObject json = new JSONObject(text);
    	JSONObject DB = json.getJSONObject(dbParam);
    	
    	DRIVER = DB.getString("DRIVER");
    	URL = DB.getString("URL");
    	USERNAME = DB.getString("USERNAME");
    	PASSWORD = DB.getString("PASSWORD");
    	
    	this.init();
    }
    
    private String readFile(File file){
    	String text = null;
    	
    	try{
    		if(file.isFile() && file.exists()){
    			InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");
    			BufferedReader bufferedReader = new BufferedReader(read);
    			String lineTxt = null;
    			
    			while((lineTxt = bufferedReader.readLine()) != null){
    				text += lineTxt;
    			}
    			read.close();
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	
    	return text;
    }
    
    private String getCurrentPath(){
		String rootPath = null;
		
		java.net.URL url = ConnectionUtil.class.getProtectionDomain().getCodeSource().getLocation();
		String filePath = null;
		
		try{
			filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8");
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		if(filePath.endsWith(".jar")){
			filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
		}
		
		java.io.File file = new java.io.File(filePath);
		rootPath = file.getAbsolutePath();
		
		rootPath = rootPath.substring(0, rootPath.lastIndexOf("\\"));
		rootPath += "\\classes";
		
		return rootPath;
    }
    
   
    public Connection getConnection(){
        try{
            conn = DriverManager.getConnection(URL, USERNAME,  
                    PASSWORD);
        }catch (SQLException e){  
            System.out.println(e.getMessage());  
        }
        
        return conn;
    }

    public int executeUpdate(String sql, Object[] params){
        int affectedLine = 0;
        
        try{   
            conn = this.getConnection();
   
            pstmt = conn.prepareStatement(sql);  
  
            if (params != null){  
                for (int i = 0; i < params.length; i++){  
                    pstmt.setObject(i + 1, params[i]);
                }  
            }
               
            affectedLine = pstmt.executeUpdate();  
  
        }catch (SQLException e){  
            System.out.println(e.getMessage());  
        }finally {   
            closeAll();  
        }
        
        return affectedLine;  
    }
  
    /** 
     * SQL 查询将查询结果直接放入ResultSet中
     */  
    private ResultSet executeQueryRS(String sql, Object[] params){  
        try{
            conn = this.getConnection();  
                
            pstmt = conn.prepareStatement(sql);  
                
            if (params != null){  
                for (int i = 0; i < params.length; i++){  
                    pstmt.setObject(i + 1, params[i]);  
                }  
            }
            
            resultSet = pstmt.executeQuery();  
  
        }catch (SQLException e){  
            System.out.println(e.getMessage());  
        }
  
        return resultSet;  
    }  
  
    /** 
     * 获取结果集,并将结果放在List中
     */  
    public List<Object> excuteQuery(String sql, Object[] params){   
        ResultSet rs = executeQueryRS(sql, params);  
         
        ResultSetMetaData rsmd = null;  
         
        int columnCount = 0;  
        try{  
            rsmd = rs.getMetaData();  
             
            columnCount = rsmd.getColumnCount();  
        }catch (SQLException e1) {  
            System.out.println(e1.getMessage());  
        }  
  
        List<Object> list = new ArrayList<Object>();  
  
        try{    
            while (rs.next()) {  
                Map<String, Object> map = new HashMap<String, Object>();  
                for (int i = 1; i <= columnCount; i++) {  
                    map.put(rsmd.getColumnLabel(i), rs.getObject(i));  
                }  
                list.add(map);  
            }  
        }catch (SQLException e) {  
            System.out.println(e.getMessage());  
        }finally {   
            closeAll();
        }
  
        return list;  
    }  
      
    /** 
     * 存储过程带有一个输出参数的方法 
     * @param sql 存储过程语句 
     * @param params 参数数组 
     * @param outParamPos 输出参数位置 
     * @param SqlType 输出参数类型 
     * @return 输出参数的值 
     */  
    public Object excuteQuery(String sql, Object[] params,int outParamPos, int SqlType){  
        Object object = null;  
        conn = this.getConnection();  
        
        try{   
            callableStatement = conn.prepareCall(sql);  
             
            if(params != null){  
                for(int i = 0; i < params.length; i++) {  
                    callableStatement.setObject(i + 1, params[i]);  
                }  
            }  
             
            callableStatement.registerOutParameter(outParamPos, SqlType);  
              
            callableStatement.execute();  
             
            object = callableStatement.getObject(outParamPos);  
              
        }catch (SQLException e){  
            System.out.println(e.getMessage());  
        }finally{   
            closeAll();
        }  
          
        return object;  
    }  
  
    private void closeAll(){   
        if (resultSet != null){  
            try {  
                resultSet.close();  
            } catch (SQLException e){  
                System.out.println(e.getMessage());  
            }  
        }  
    
        if(pstmt != null){  
            try{  
                pstmt.close();  
            } catch (SQLException e){  
                System.out.println(e.getMessage());  
            }  
        }  
          
        if(callableStatement != null){  
            try{  
                callableStatement.close();  
            }catch (SQLException e) {  
                System.out.println(e.getMessage());  
            }  
        }  
   
        if(conn != null){  
            try{  
                conn.close();  
            } catch (SQLException e) {  
                System.out.println(e.getMessage());  
            }  
        }     
    }  
}

使用方法:

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

{
	"DB":{
		"DRIVER"  :"com.microsoft.sqlserver.jdbc.SQLServerDriver",
		"URL"     :"jdbc:sqlserver://223.68.143.21:12922;DatabaseName=TwRailway_ECP",
		"USERNAME":"sa",
		"PASSWORD":"senao"
	}
}
其中,DB可以有多个

工程导入JAR包之后,通过

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包。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值