JDBC系列:(2.5)创建JDBCUtils工具类

发布时间:2020-06-24 05:31:22 作者:lsieun
来源:网络 阅读:576


1、建立db.properties文件

url=jdbc:mysql://localhost:3306/testdb
user=root
password=root
driverClass=com.mysql.jdbc.Driver



2、JDBC工具类:JDBCUtil.java

package com.rk.db.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * JDBC的工具类
 * @author RK
 *
 */
public class JDBCUtil
{
	private static final String url;
	private static final String user;
	private static final String password;
	private static final String driverClass;
	
	/**
	 * 静态代码块中(只加载一次)
	 */
	static
	{		
		try
		{
			//读取db.properties文件
			InputStream inStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
			
			Properties props = new Properties();
			//加载文件
			props.load(inStream);
			//读取信息
			url = props.getProperty("url");
			user = props.getProperty("user");
			password = props.getProperty("password");
			driverClass = props.getProperty("driverClass");
			
			//注册驱动程序
			Class.forName(driverClass);
		}
		catch (IOException e)
		{
			System.out.println("读取数据库配置文件出错");
			throw new RuntimeException(e);
		}
		catch (ClassNotFoundException e)
		{
			System.out.println("数据库驱程程序注册出错");
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 获取数据库的连接
	 * @return 数据库连接
	 */
	public static Connection getConnection()
	{
		try
		{
			return DriverManager.getConnection(url,user,password);
		}
		catch (SQLException e)
		{
			System.out.println("获取数据库连接出错");
			throw new RuntimeException(e);
		}		
	}
	
	/**
	 * 关闭Connection、Statement和ResultSet
	 * @param conn 数据库连接
	 * @param stmt	执行SQL语句的命令
	 * @param rs 结果集
	 */
	public static void close(Connection conn,Statement stmt,ResultSet rs)
	{
		closeQuietly(rs);
		closeQuietly(stmt);
		closeQuietly(conn);
	}
	
	/**
	 * 安静的关闭数据库资源
	 * @param ac 实现了AutoCloseable接口的对象
	 */
	public static void closeQuietly(AutoCloseable ac)
	{
		if(ac != null)
		{
			try
			{
				ac.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}




推荐阅读:
  1. SqlServer系列笔记——表的创建维护
  2. JDBC系列:(7)使用Connection操作事务

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jdbc jdb %util

上一篇:密码学与身份鉴别技术--PKI原理与实战应用篇<2>

下一篇:Outlook 获取联系人名片对象为空

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》