Oracle连接数据库的封装类OracleDB
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class OracleDB {
//连接字符串 "jdbc:oracle:thin:@localhost:1521:数据库实例名"
static String url = "jdbc:oracle:thin:@localhost:1521:database";
static String user = "scott"; //数据库登陆名
static String password = "tiger"; //数据库登陆密码
static {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");//加载驱动 < 需要导入驱动包>
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//数据库连接的方法
public static Connection getConn() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
//关闭连接的方法
public static void close(Connection conn, Statement st, ResultSet rs) {
//从小到大关闭连接
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}