将java连接数据库的代码封装成一个新的类,在日后写其他代码时候会简洁许多!
程序员文章站
2022-06-10 15:06:53
...
package com.entor.jdbc;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class DBUtil {
//返回数据库连接
public static Connection getConnection() {
Connection conn = null;
try {
Properties prop = new Properties();
prop.load(new FileInputStream("config/db.properties"));
Class.forName(prop.getProperty("driver"));
conn = DriverManager.getConnection(prop.getProperty("url"),
prop.getProperty("username"),
prop.getProperty("password"));
}catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 通过ResultSet关闭数据库连接
* @param rs
*/
public static void close(ResultSet rs) {
try {
Statement stmt = rs.getStatement();
Connection conn = stmt.getConnection();
rs.close();
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过Statement关闭数据库连接
* @param stmt
*/
public static void close(Statement stmt) {
try {
Connection conn = stmt.getConnection();
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
所读取的文件信息为:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
username=scott
password=tiger
上一篇: 模板类的特化和类型萃取
下一篇: 羊肉有味道了用什么方法去除