关于JDBC的几个工具方法

//Geeksun 2018.07.30
package com.geeksun.one

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

public class JDBCTools
{
	public static Connection GetConnection() throws Exception
	{
		/*
		*用类名.class.getClassLoader().getResourceAsStream(文件名);来获得bin目录下的指定文件输入流
		*在eclipse中将properties新建到src中会自动复制到bin目录,这样在交付软件的时候就不用在手动复制配置文件或修改代码了
		*/
		//文件夹中有个JDBC.properties存放数据库的账号信息
		Properties properties = new Properties();
		InputStream ins = JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
		//以简单的线性格式从输入字符流读取属性列表(关键字和元素对)。 
		properties.load(ins);
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		String jdbcUrl = properties.getProperty("jdbcUrl");
		String driver = properties.getProperty("driver");
		//装载类
		Class.forName(driver);
		return DriverManager.getConnection(jdbcUrl,user,password);
	}
	public static void release(Connection conn,Statement statement,ResultSet rs)
	{
		//先开的后关闭,后开的先关闭!!!
		if(rs != null)
		{
			try{
				rs.close();
			}catch(SQLException e)
			{
				e.printStackTrace();
			}
		}
		if(statement != null)
		{
			try{
				statement.close();
			}catch(SQLException e)
			{
				e.printStackTrace();
			}
		}
		if(conn != null)
		{
			try{
				conn.close();
			}catch(SQLException e)
			{
				e.printStackTrace();
			}
		}	
	}
}

猜你喜欢

转载自blog.csdn.net/Geek_sun/article/details/81286303
今日推荐