用户登录

 数据库工具类
 * 	1、打开数据库连接
 * 	2、关闭资源
 * 
 * 	常见的报错情况:
 * 		1、数据库的jar包未拷贝到lib目录下
 * 			java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
 * 		2、数据库的密码可能不正确:
 * 			java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
 * 		3、数据库名称不正确
 * 			com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'java29'
 * 
 * 
 * 
 *
 */
public class DBUtil {

	// 得到配置文件对象
	private static Properties properties = new Properties();
	
	static {
		try {
			// 得到db.properties的输入流对象
			InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
			// 通过properties的load()方法,加载配置文件的输入流
			properties.load(inputStream);
		} catch (Exception e) {
			// 打印异常
			e.printStackTrace();
		}
	}
	
	/**
	 * 得到数据库连接
	 * 	1、加载驱动
	 * 	2、通过地址、账号、密码得到数据库连接
	 * @return
	 */
	public static Connection getConnection() {
		Connection connection = null;
		
		// 从配置对象中获取参数   getProperty()
		String jdbcName = properties.getProperty("jdbcName");
		String dbUrl = properties.getProperty("dbUrl");
		String dbName = properties.getProperty("dbName");
		String dbPwd = properties.getProperty("dbPwd");
		
		try {
			//	1、加载驱动
			Class.forName(jdbcName);
			// 2、通过地址、账号、密码得到数据库连接
			connection = DriverManager.getConnection(dbUrl, dbName, dbPwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	
	/**
	 * 关闭资源
	 * @param connection
	 * @param preparedStatement
	 * @param resultSet
	 */
	public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
		// 关闭资源
		try {
			// 先判断不为空,再关闭
			if (resultSet != null) {
				resultSet.close();
			}
			if (preparedStatement != null) {
				preparedStatement.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	public static void main(String[] args) {
		System.out.println(getConnection());
	}
	
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值