/**
*
*/
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author jcuckoo
*
* 2014-8-11 上午11:13:00
*/
public class DBUtil {
private static String driverName="oracle.jdbc.driver.OracleDriver";
private static String url="jdbc:oracle:thin:@localhost:1521:oracle";
private static String userName="scott";
private static String userPwd="tiger";
private static Connection conn=null;
private static Statement stmt=null;
private static ResultSet rs=null;
public static Connection getConnection() throws ClassNotFoundException, SQLException{
//1.加载 JDBC 驱动程序
Class.forName(driverName);
//2.建立与数据库的连接
if(conn==null||conn.isClosed()){
conn=DriverManager.getConnection(url,userName,userPwd);
}
return conn;
}
public static int executeUpdate(String sql) {
int result=0;
try {
getConnection();
//3.准备SQL
stmt=conn.createStatement();
//4.执行更新操作
result = stmt.executeUpdate(sql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//释放资源
closeAll();
return result;
}
public static ResultSet executeQuery(String sql){
try {
getConnection();
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static void closeAll(){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(stmt!=null){
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}