JDBC的Dao层进行抽象(万能增删改、查语句)+ 读取jdbc.properties进行连接mysql

jdbc.properties

db.driverClass=com.mysql.cj.jdbc.Driver
db.jdbcUrl=jdbc:mysql://localhost:3306/java2013?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=true&allowMultiQueries=true
db.username=root
db.password=123456

DBUtil.java类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DBUtil {
	private static final char UNDER_LINE = '_';
	private static final String DRIVER_NAME;
	private static final String JDBC_URL;
	private static final String USER_NAME;
	private static final String USER_PASS;

	static {
		Properties properties = new Properties();
		try {
			InputStream inStream = new FileInputStream(new File("src/jdbc.properties"));
			properties.load(inStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		DRIVER_NAME = properties.getProperty("db.driverClass");
		JDBC_URL = properties.getProperty("db.jdbcUrl");
		USER_NAME = properties.getProperty("db.username");
		USER_PASS = properties.getProperty("db.password");

	}

	// userName->setUserName
	public static String buildSetterMethodName(String field) {
		StringBuilder builder = new StringBuilder();
		char firstChar = field.charAt(0);
		builder.append("set").append(Character.toUpperCase(firstChar)).append(field.substring(1));
		return builder.toString();
	}

	// userName->USER_NAME
	public static String fieldToColumn(String field) {
		StringBuilder builder = new StringBuilder();
		char[] ch = field.toCharArray();
		for (char c : ch) {
			if (Character.isUpperCase(c)) {
				builder.append(UNDER_LINE);
			}
			builder.append(Character.toUpperCase(c));
		}
		return builder.toString();
	}

	// 查询语句
	public static <T> List<T> executeQuery(Class<T> clazz, String sql, Object... args) {
		List<T> list = new ArrayList<T>();
		// 得到数据库的链接
		Connection connection = getConnection();
		if (connection != null) {
			// 预编译的Statement的对象
			PreparedStatement ps = null;
			// 结果集对象
			ResultSet rs = null;
			try {
				// 通过数据库链接的prepareStatement完成SQL语句的预编译
				ps = connection.prepareStatement(sql);

				// 判断传入的可变参数有数据
				if (args != null && args.length > 0) {
					int parameterIndex = 1;
					for (Object arg : args) {
						ps.setObject(parameterIndex, arg);
						parameterIndex++;
					}
				}

				rs = ps.executeQuery();
				// 通过clazz对象得到类中所有的属性的集合
				Field[] fields = clazz.getDeclaredFields();
				// 遍历结果集
				while (rs.next()) {
					try {
						// 通过newInstance 得到类的实例
						T object = clazz.newInstance();
						for (Field field : fields) {
							if (field.getModifiers() == Modifier.PRIVATE) {
								// 通过属性的名称->表中字段名称
								String columnName = fieldToColumn(field.getName());
								// 通过表中字段名称->得到对应的值
								Object columnValue = rs.getObject(columnName);
								// 通过属性名->set方法名
								String setMethodName = buildSetterMethodName(field.getName());

								// getObject()对于时间默认是java.sql.date,
								// 而我们需要java.sql.datetime,对应于getTimestamp()
								if ("java.util.Date".equals(field.getType().getName())) {
									// 由于时间的特殊性,对columnValue重新赋值
									columnValue = rs.getTimestamp(columnName);
								}

								// 根据setter方法名称得到Method的实例
								Method setMethod = clazz.getMethod(setMethodName, field.getType());
								// 让方法自运行
								setMethod.invoke(object, columnValue);
							}
						}
						list.add(object);
					} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException
							| IllegalArgumentException | InvocationTargetException e) {
						e.printStackTrace();
					}
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	// 执行CDU
	public static int executeUpdate(String sql, Object... args) {
		Connection connection = getConnection();
		PreparedStatement statement = null;
		try {
			statement = connection.prepareStatement(sql);
			if (args != null && args.length > 0) {
				int i = 1;
				for (Object arg : args) {
					statement.setObject(i, arg);
					i++;
				}
			}
			int result = statement.executeUpdate();
			return result;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (statement != null) {
					statement.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		return 0;
	}

	public static Connection getConnection() {
		Connection connection = null;
		try {
			// 加载驱动
			Class.forName(DRIVER_NAME);
			// 得到数据库连接
			connection = DriverManager.getConnection(JDBC_URL, USER_NAME, USER_PASS);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return connection;
	}

}

UserDao.java

public List<User> select(User user) {
		String sql = "SELECT ROW_ID,USER_NO,USER_PASS_WORD,USER_NAME,LOGIN_TIME FROM k_user where USER_NO=? and USER_PASS_WORD=?";
		List<User> list = DBUtil.executeQuery(User.class, sql, user.getUserNo(), user.getUserPassWord());
		return list;
	}

测试类

@Test
public void test4() {
	User user = new User();
	user.setUserNo("20170300520");
	user.setUserPassWord("123456");
	UserDao dao = new UserDao();
	System.out.println(dao.select(user));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值