Java中JDBC工具类

项目结构

Java中JDBC工具类_第1张图片

详细代码

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,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:
可修改用户名,密码,url地址

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 void main(String[] ages) {
		String userName = properties.getProperty("db.username");
		System.out.print(userName);
	}
	
	public static String getValue(String key) {
		return properties.getProperty(key);
	}
}

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 LYT
 */
public class DBLink {

	private Logger logger = Logger.getLogger(DBLink.class);
	
	/**
	 * 获取数据库连接
	 *
	 * @author LYT
	 */
	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) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 查询数据
	 *
	 * @author LYT
	 */
	public void select(String sql, IRowMapper rowMapper) {// 接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();// 获取连接
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);// 执行sql,将查询的数据存到ResultSet类型的变量中
			rowMapper.rowMapper(resultSet);// 因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法 多态
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(resultSet, statement, connection);
		}
	}
	
	/**
	 * 查询数据
	 *
	 * @author LYT
	 */
	public void select(String sql, IRowMapper rowMapper, 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类型的变量中
			rowMapper.rowMapper(resultSet);// 因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法 多态
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(resultSet, preparedStatement, connection);
		}
	}

	/**
	 * 判断SQL语句是否能查出数据
	 *
	 * @author LYT
	 */
	public boolean exist(String sql) {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery("select id,name,mobile,address from first_class");
			return resultSet.next();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(resultSet, statement, connection);
		}
		return false;
	}
	
	/**
	 * 判断SQL语句是否能查出数据
	 *
	 * @author LYT
	 */
	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) {
			e.printStackTrace();
		} finally {
			close(resultSet, preparedStatement, connection);
		}
		return false;
	}

	/**
	 * 修改(insert、update和delete)数据
	 *
	 * @author LYT
	 */
	public boolean update(String sql) {
		Connection connection = null;
		Statement statement = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			int result = statement.executeUpdate(sql);
			// statement.close();//如果上面代码出现异常,则该行代码及其下面代码无法执行,比如sql语句语法错误,则statement和connection无法释放
			// connection.close();
			return result > 0;// 处理结果
		} catch (Exception e) {
			e.printStackTrace();
		} finally {// 即便有异常也会执行代码
			close(statement, connection);
		}
		return false;
	}

	/**
	 * 修改(insert、update和delete)数据
	 *
	 * @author LYT
	 */
	public boolean update(String sql, Object... params) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);// 不完整的sql,含有?占位符的sql
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i + 1, params[i]);// 为?赋值
			}
			return preparedStatement.executeUpdate() > 0;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(preparedStatement, connection);
		}
		return false;
	}
	
	/**
	 * 释放资源
	 *
	 * @author LYT
	 */
	private void close(Statement statement, Connection connection) {
		try {
			if (statement != null) {// 可能由于异常导致statement没有赋值,比如url出错
				statement.close();
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 释放资源
	 *
	 * @author LYT
	 */
	private void close(ResultSet resultSet, Statement statement, Connection connection) {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		close(statement, connection);
	}
}

Test:

package com.jd.test;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.jd.tool.db.DBLink;
import com.jd.tool.db.IRowMapper;

public class Test2 {

	// SQL注入:改变原有sql语句含义,产生意想不到的结果
	public static void main(String[] args) {

		String userName = "a";
		String password = "1' or '1'='1";
		String sql = "select id from user_info where user_name=? and password=?";
		System.out.println(sql);

		class RowMapper implements IRowMapper {
			@Override
			public void rowMapper(ResultSet rs) {
				try {
					if (rs.next()) {
						System.out.println("Yes");
					} else {
						System.out.println("No");
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		RowMapper rowMapper = new RowMapper();
		new DBLink().select(sql, rowMapper, userName, password);
	}
}

你可能感兴趣的:(Java中JDBC工具类)