JAVA高手解疑

2025-04-08 16:01:41
推荐回答(1个)
回答1:

是不是连接池名字写错了?

import java.sql.*;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class conn
{
private Connection conn=null;
private static conn p = null;

private Statement stmt = null;
private ResultSet rs = null;
private PreparedStatement ps=null;

public synchronized Connection getConnection() throws Exception{
try{
Context initCtx=new javax.naming.InitialContext();
//从Context中lookup数据源
Context envCtx=(Context)initCtx.lookup("java:comp/env");
DataSource ds=(DataSource)envCtx.lookup("jdbc/examonline");
return ds.getConnection();
}
catch(SQLException e){
throw e;
}
catch(NamingException e){
throw e;
}
}
private conn(){
try{
this.conn = this.getConnection();
this.stmt = this.conn.createStatement();
}
catch(Exception e)
{
}
}

//实现单态
public static conn createInstance(){
if(p==null){
p = new conn();
}
return p;

}
//执行查询
public void Query(String sql){
try {
this.rs = this.stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
//return rs;
}

public ResultSet Query2(){
try {
this.rs =this.ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

//执行更新
public void Update(String sql){
try {
this.stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}

public boolean Update2(){
try {
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 用于获得执行SQL语句的PreparedStatement(预处理)对象
*/
public PreparedStatement setPs(String sql){
try{
ps=conn.prepareStatement(sql);
return ps;
}
catch(Exception e){}
return null;
}
public PreparedStatement getPs() {
return ps;
}

/**
* 关闭连接
*/
public void closeCon(){
try{
if(this.conn!=null)
this.conn.close();
if(this.rs!=null)
this.rs.close();
if(this.ps!=null)
this.ps.close();
p = null;
}catch(Exception e){
e.printStackTrace();
}
}

public ResultSet getRs() {
return rs;
}

public void setRs(ResultSet rs) {
this.rs = rs;
}