自定义JDBC工具类

自定义JDBC工具类
         1.加载驱动
         2.获取连接对象
         3.关闭连接
     

public class JDBCUtils {
	private static String url = null;
	private static String user = null;
	private static String password = null;
	private static String driverClass = null;
	private static InputStream in = null;

	// 利用静态代码块的特征,在类文件加载到内存的时候,就会执行静态代码块里面的代码
	static {

		try {
			// 1.读取配置文件信息,读取properties文件
			Properties props = new Properties();

			// 如果一个properties文件加载到内存中,需要借助IO流
			in = new FileInputStream("./src/db.properties");

			// 2.利用Properties里面的load方法加载文件
			props.load(in);

			// 3.可以通过properties类对象,获取到想要的数据
			url = props.getProperty("url");
			user = props.getProperty("user");
			password = props.getProperty("password");
			driverClass = props.getProperty("driver");

			// 4.加载类文件
			Class.forName(driverClass);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("加载驱动失败");
		} finally {
			// 关闭文件连接
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}

	/**
	 * 获取数据库连接的对象
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection con = null;

		try {
			con = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}

	/**
	 * 关闭数据库连接,释放statement
	 * 
	 * @param conn 数据库连接对象
	 * @param stmt statement对象
	 */
	public static void close(Connection conn, Statement stmt) {
		try {
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 关闭数据库连接,释放statement和ResultSet
	 * 
	 * @param conn 数据库连接对象
	 * @param stmt Statement对象
	 * @param rs   结果集对象
	 */
	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}


     把连接数据库需要的信息都保存在一个文件中,这个文件是一个properties文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myuser?useSSL=true
user=root
password=beijing

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值