连接数据库类

/**
 * 
 */
package com.jcuckoo.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * @author jcuckoo
 *
 * 2014-8-11 上午11:13:00
 */
public class DBOperator {
private final static String driverName="oracle.jdbc.driver.OracleDriver";
private final static String url="jdbc:oracle:thin:@localhost:1521:oracle";
private final static String userName="scott";
private final static String userPwd="tiger";

private static Connection conn=null;
private static PreparedStatement pst=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,Object []params) {
int result=0;
try {
getConnection();
//3.准备SQL
pst=conn.prepareStatement(sql);
//参数赋值
if(params!=null){
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1, params[i]);
}
}

//4.执行更新操作
result = pst.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//释放资源
closeAll();
return result;
}
public static ResultSet executeQuery(String sql,Object []params){
try {
getConnection();
//ResultSet.TYPE_FORWARD_ONLY   (略)  
//ResultSet.TYPE_SCROLL_INSENSITIVE  双向滚动,但不及时更新,就是如果数据库里的数据修改过,并不在ResultSet中反应出来。  
//ResultSet.TYPE_SCROLL_SENSITIVE  双向滚动,并及时跟踪数据库里的更新,以便更改ResultSet中的数据。  
//ResultSet.CONCUR_READ_ONLY  只读取ResultSet  
//ResultSet.CONCUR_UPDATABLE  用ResultSet更新数据库
pst=conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
//参数赋值
if(params!=null){
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1, params[i]);
}
}
rs=pst.executeQuery();
} 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(pst!=null){
pst.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值