JDBC工具类

项目结构:

log4j.properties:

# DEBUG\u8BBE\u7F6E\u8F93\u51FA\u65E5\u5FD7\u7EA7\u522B\uFF0C\u7531\u4E8E\u4E3ADEBUG\uFF0C\u6240\u4EE5ERROR\u3001WARN\u548CINFO \u7EA7\u522B\u65E5\u5FD7\u4FE1\u606F\u4E5F\u4F1A\u663E\u793A\u51FA\u6765
log4j.rootLogger=DEBUG,Console,RollingFile

#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u63A7\u5236\u53F0
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
#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u64CD\u4F5C\u7CFB\u7EDFD\u76D8\u6839\u76EE\u5F55\u4E0B\u7684log.log\u6587\u4EF6\u4E2D
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

db.properties:

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

PropertiesTool:

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流对象
    try {
      properties.load(inputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static String getVaule(String key) {
	  return properties.getProperty(key);
  }
  public static void main(String [] args) {
   
  }
}

IRowmapper:

package com.jd.tool.db;

import java.sql.ResultSet;

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

DBLink:

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;
/**
 * 数据库管理工具类
 *
 * @author 心游
 */
public class DBLink {
	private static Logger logger = Logger.getLogger(DBLink.class);
	/**
	 * 获取连接
	 *
	 * @author 心游
	 */
	public static Connection getConnection() {//增删改查都需要进行这一步骤,这可以简化代码
	      try {
			Class.forName("com.mysql.jdbc.Driver");//加载驱动
			  String url = PropertiesTool.getVaule("db.url");
			  String userName = PropertiesTool.getVaule("db.username");
			  String password = PropertiesTool.getVaule("db.password");
			  return DriverManager.getConnection(url, userName, password);//获取连接,产生每一个对象代表一次数据库连接
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}
		return null;
	}
	
	/**
	 * 修改(delete,update,insert)数据
	 *
	 * @author 心游
	 */
	public boolean update(String sql) {
		Connection connection =null;
		Statement statement = null;
		try {
			connection = getConnection();
			System.out.println(connection);
			statement = connection.createStatement();//获取statement对象
			int affect = statement.executeUpdate(sql);//执行sql语句,返回影响行数
			if(affect>0) {
				System.out.println("OK");
			}else
			System.out.println("NO");
			statement.close();/*如果上面代码出现异常,则该行代码及其下面代码无法执行,所以资
			  源无法释放;比如sql语句语法错误,则statement和connection无法释放*/
		      connection.close();
			return affect>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}finally {
		      close(statement,connection);
		}
		return false;
	}
	
	/**
	 * 修改(delete,update,insert)数据
	 *
	 * @author 心游
	 */
	public static boolean update(String sql ,Object ...pramas) {//与上面的不同之处:可以处理这样的形式String where = "123 'or' 1 '=' 1";
		Connection connection =null;
		PreparedStatement preparedStatement = null;
		try {
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);//
			for (int i = 0; i < pramas.length; i++) {
				preparedStatement.setObject(i+1,pramas[i]);//为?赋值
			}
			return preparedStatement.executeUpdate()>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}finally {
		      close(preparedStatement,connection);
		}
		return false;
	}
	
	/**
	 * 查找数据
	 *
	 * @author 心游
	 */
	public static void select(String sql,IRowMapper rowMapper,Object ...pramas) {
	    Connection connection = null;
	    PreparedStatement preparedStatement =null;
	    ResultSet resultSet=null;
	    try {
	      connection = getConnection();
	      preparedStatement = connection.prepareStatement(sql);
	      for (int i = 0; i < pramas.length; i++) {
				preparedStatement.setObject(i+1,pramas[i]);//为?赋值
			}
	      resultSet= preparedStatement.executeQuery();
	      rowMapper.rowMapper(resultSet);
	    } catch (Exception e) {
	    	logger.debug(e.getMessage(),e);
	    }finally {
		      close(preparedStatement,connection,resultSet);
	    }
	}
	
	/**
	 * 判断SQL语句是否能查出数据
	 *
	 * @author 心游
	 */
	public static boolean exist(String sql) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
	    Connection connection = null;
	    Statement statement =null;
	    ResultSet resultSet=null;
	    try {
	      connection = getConnection();
	      statement = connection.createStatement();
	      resultSet= statement.executeQuery(sql);//执行sql,将查询的数据存到ResultSet类型的变量中
	      return resultSet.next();
	    } catch (Exception e) {
	    	logger.debug(e.getMessage(),e);
	    }finally {
	      close(statement,connection,resultSet);
	    }
	    return false;
	}
	
	/**
	 * 判断SQL语句是否能查出数据
	 *
	 * @author 心游
	 */
	public static boolean exist(String sql,Object ...params) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
	    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();//执行sql,将查询的数据存到ResultSet类型的变量中
	      return resultSet.next();
	    } catch (Exception e) {
	    	logger.debug(e.getMessage(),e);
	    }finally {
	      close(preparedStatement,connection,resultSet);
	    }
	    return false;
	  }
	
	/**
	 * 释放内存
	 *
	 * @author 心游
	 */
	private static void close(Statement statement,Connection connection) {
		try {
	        if(statement!=null) {
	          statement.close();
	        }
	      } catch (SQLException e) {
	        e.printStackTrace();
	      }
	      try {
	        if(connection!=null) {
	          connection.close();
	        }
	      } catch (SQLException e) {
	    	  logger.debug(e.getMessage(),e);
	      }
	}
	
	/**
	 * 释放内存
	 *
	 * @author 心游
	 */
	private static void close(Statement statement,Connection connection,ResultSet resultSet) {
		 try {
		        if(resultSet!=null) {
		          resultSet.close();
		        }
		      } catch (SQLException e) {
		        e.printStackTrace();
		      }
		
		try {
	        if(statement!=null) {
	          statement.close();
	        }
	      } catch (SQLException e) {
	        e.printStackTrace();
	      }
	      try {
	        if(connection!=null) {
	          connection.close();
	        }
	      } catch (SQLException e) {
	    	  logger.debug(e.getMessage(),e);
	      }
	}
	
	
}

Test:

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、付费专栏及课程。

余额充值