- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.util.Properties;
- public class JdbcTools {
- //properties文件名
- private static String defaultName = "jdbc.properties";
- /**
- * 获取Connection
- * @return connection
- * @throws Exception
- */
- public static Connection getConnection() throws Exception{
- Connection connection = getConnection(defaultName);
- return connection;
- }
- /**
- * 通过properties文件名获取Connection
- * @param fileName properties文件名
- * @return Connection
- * @throws Exception
- */
- public static Connection getConnection(String fileName) throws Exception{
- //IO流读取jdbc.properties文件
- InputStream in = JdbcTools.class.getClassLoader().getResourceAsStream(fileName);
- // 读取参数
- Properties p = new Properties();
- p.load(in);
- String url = p.getProperty("url");
- String user = p.getProperty("user");
- String password = p.getProperty("password");
- String driver=p.getProperty("driver");
- Class.forName(driver);
- Connection connection = DriverManager.getConnection(url, user, password);
- if (in!=null) {
- in.close();
- }
- return connection;
- }
- }
来源: