运行时需要用到的类包:
commons-dbcp-1.2.2.jar ojdbc14.jar commons-pool.jar commons-collections.jar
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.commons.dbcp.BasicDataSource;
public class TestDbcp {
private static Connection con = null;
private static PreparedStatement st = null;
private static ResultSet rs = null;
private static BasicDataSource ds = null;
private static void init() {
try {
ds = new BasicDataSource();
// ds.setInitialSize(1);
ds.setMaxIdle(1);
ds.setMaxActive(3);
ds.setUsername("sec");
ds.setPassword("sec");
ds.setUrl("jdbc:oracle:thin:@10.1.252.80:1521:newngboss");
ds.setDriverClassName("oracle.jdbc.OracleDriver");
con = ds.getConnection();
System.out.println("获取连接成功");
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("连接失败:" + ex.getMessage());
}
}
private static void query() {
try {
st = con.prepareStatement("select * from SEC_OPERATOR where code=? ");
st.setString(1, "8002");
rs = st.executeQuery();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void close() {
try {
if (rs != null)
rs.close();
} catch (Exception ex) {
}
try {
if (st != null)
st.close();
} catch (Exception ex) {
}
try {
if (con != null)
con.close();
System.out.println("关闭连接成功");
} catch (Exception ex) {
}
try {
if (ds != null)
ds.close();
System.out.println("关闭连接成功");
} catch (Exception ex) {
}
}
public static void main(String args[]) {
init();
query();
close();
}
}