(4)JDBCTools(调用连接和关闭数据库的方法)

jdbc.properties:我们在当前包底下创建一个File 命名为
url 是我们导入的mysql-connection的jar包
我们一般是把jar包放到新建的lib下面
查看url的具体步骤是:
打开该项目的Referenced Libraries

jdbc.properties 配置文件内容
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/atguigu
user=root
password=

我们新建一个类 命名为 JDBCTools 可以快速 调用方法(连接和关闭)

获取连接的方法
通过读取配置文件从数据库服务器获取一个连接.

	public static Connection getConnection() throws Exception
	{
		//1.  准备连接数据库的4个字符串
		String driver = null;
		String jdbcUrl = null;
		String user = null;
		String password = null;
		//1).创建Properties 对象
		Properties properties = new Properties();
		//2)。 获取jdbc.properties 对应的输入流
		InputStream in = 
				JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
		
		//3). 加载2) 对应的输入流
		properties.load(in);
		
		//4). 具体决定user , password 等4个字符串
		driver = properties.getProperty("driver");
		jdbcUrl = properties.getProperty("jdbcUrl");
		user = properties.getProperty("user");
		password = properties.getProperty("password");
		
		//2.加载数据库驱动程序(对应的Driver 实现类中有注册驱动的静态代码块)
		Class.forName(driver);
		
		//3. 通过DriverManager 的getConnection() 方法获取数据库连接.
		return DriverManager.getConnection(jdbcUrl, user, password);
	}


**关闭数据库**  :Statement , Connection
	/**
	 * 关闭Statement 和Connection
	 */
	public static void release(Statement statement,Connection conn)
	{
		if(statement!=null)
		{
			try {
				statement.close();
			}catch(Exception e2){
				e2.printStackTrace();
			}
		}
		//*******
		if(conn!=null)
		{
			try {
			conn.close();
			}catch(Exception e2){
				e2.printStackTrace();
			}
		}
	}

**关闭数据库2**  方法重载 ---- 关闭ResultSet , Statement , Connection
	public static void release(ResultSet rs,
			Statement statement,Connection conn)
	{
		if(rs != null)
		{
			try {
				rs.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		if(statement!=null)
		{
			try {
				statement.close();
			}catch(Exception e2){
				e2.printStackTrace();
			}
		}
		
		//********
		if(conn!=null)
		{
			try {
			conn.close();
			}catch(Exception e2){
				e2.printStackTrace();
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/Yuz_99/article/details/84147682
今日推荐