Java jdbc 连接oracle之三(封装工具类)

时间:2021-10-16 13:54:13
driver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@192.168.10.105:1521:orcl
user = LF
password = LF
package com.lf.testdatabase;

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