Java中JDBC工具类

一、项目结构:

二、工具类:

1、log4j.properties:

# DEBUG设置输出日志级别,由于为DEBUG,所以ERROR、WARN和INFO 级别日志信息也会显示出来
log4j.rootLogger=DEBUG,RollingFile

#将日志信息输出到控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= [%-5p]-[%d{yyyy-MM-dd HH:mm:ss}] -%l -%m%n
#将日志信息输出到操作系统D盘根目录下的log.log文件中
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=D://log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n

2、db.properties:

db.username = root
db.password = root
db.url = jdbc:mysql://127.0.0.1:3306/test

3、PropertiesTool.java:

package com.jd.tool;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesTool {
	
	private static Properties properties = new Properties();
	
	static {
		InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream("db.properties");//将db.properties变为javaIO流对象inputStream
		try {
			properties.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getValue(String string) {
		return properties.getProperty(string);
	}
	
}

4、IRowMapper.java:

package com.jd.tool.db;

import java.sql.ResultSet;

public interface IRowMapper {
	void rowMapper(ResultSet rs);
}

5、DBLink.java:

package com.jd.tool.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import com.jd.tool.PropertiesTool;

public class DBLink {
	
	private Logger logger = Logger.getLogger(DBLink.class);
	
	/**
	 * 获取数据连接
	 *
	 * @author 样光伊
	 */
	private Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String userName = PropertiesTool.getValue("db.username");
			String password = PropertiesTool.getValue("db.password");
			String url = PropertiesTool.getValue("db.url");
			return DriverManager.getConnection(url,userName,password);
		}catch (Exception e) {
			//e.printStackTrace(); //将异常显示在控制台上 
			logger.debug(e.getMessage(), e);//异常将不再显示在控制台上
		}
		return null;
	}
	
	/**
	 * 判断数据是否存在
	 *
	 * @author 样光伊
	 */
	public boolean exist(String sql) { 
		Connection connection = null;                            
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			return resultSet.next(); 
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(resultSet,statement,connection);
		}
		return false;
	}
	
	/**
	 * 判断数据是否存在(避免了SQL注入)
	 *
	 * @author 样光伊
	 */
	public boolean exist(String sql,Object ...params) {  
		Connection connection = null;                            
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i+1, params[i]);
			}
			resultSet = preparedStatement.executeQuery();
			return resultSet.next(); 
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(resultSet,preparedStatement,connection);
		}
		return false;
	}
	
	/**
	 * 修改(insert、delete、update)数据
	 *
	 * @author 样光伊
	 */
	public boolean update(String sql) {
		Connection connection = null;
		Statement statement = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			int affect = statement.executeUpdate(sql);
			return affect>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(statement,connection);
		}
		return false;
	}
	
	/**
	 * 修改(insert、delete、update)数据(避免了SQL注入)
	 *
	 * @author 样光伊
	 */
	public boolean update(String sql,Object ...params) {//Object ...params是动态参数,只能放在参数列表的最后面
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {		
			connection = getConnection();	
			preparedStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i+1, params[i]);
			}
			return preparedStatement.executeUpdate()>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(preparedStatement,connection);
		}
		return false;
	}
	
	/**
	 * 查询数据
	 *
	 * @author 样光伊
	 */
	public void select(String sql,IRowMapper rowMapper) { //为什么去掉static:因为静态方法里不能直接调用非静态方法,
		Connection connection = null;                     //而getConnection() close(resultSet,statement,connection)都是非静态方法       
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			rowMapper.rowMapper(resultSet);
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(resultSet,statement,connection);
		}
	}
	
	/**
	 * 查询数据(避免了SQL注入)
	 *
	 * @author 样光伊
	 */
	public void select(String sql,IRowMapper rowMapper,Object ...params) {
		Connection connection = null;                      
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i+1,params[i]);
			}
			resultSet = preparedStatement.executeQuery();
			rowMapper.rowMapper(resultSet);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(resultSet,preparedStatement,connection);
		}
	}
	
	/**
	 * 关闭资源
	 *
	 * @author 样光伊
	 */
	private void close(Statement statement,Connection connection) {
		try {
			if(statement!=null) {
				statement.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
		try {
			if(connection!=null) {
				connection.close();
			}
		}catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
	}
	
	/**
	 * 关闭资源
	 *
	 * @author 样光伊
	 */
	private void close(ResultSet resultSet,Statement statement,Connection connection) {
		try {
			if(resultSet!=null) {
				resultSet.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
		close(statement,connection);
	}
	
}

三、Test.java:

package com.jd.test;

public class Test{
    public static void main(String [] args){

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值