Java 如何通过以下几种方法关闭resultSet、prepareStatement和conn,以避免rs关闭和连接池阻塞
整个数据操作如下所示。我想关闭每一个资源而不干扰下一个连接。我是否应该将构造函数更改为connection()方法,然后再更改为disconnect()方法,但这样做之后,我应该在哪里更改Java 如何通过以下几种方法关闭resultSet、prepareStatement和conn,以避免rs关闭和连接池阻塞,java,jdbc,prepared-statement,resultset,Java,Jdbc,Prepared Statement,Resultset,整个数据操作如下所示。我想关闭每一个资源而不干扰下一个连接。我是否应该将构造函数更改为connection()方法,然后再更改为disconnect()方法,但这样做之后,我应该在哪里更改 public class DataBean{ private Connection conn = null; private ResultSet res = null; private InitialContext context; private DataSource d
public class DataBean{
private Connection conn = null;
private ResultSet res = null;
private InitialContext context;
private DataSource datasource;
private Statement stmt=null;
private java.sql.PreparedStatement prepar = null;
private java.sql.CallableStatement proc = null;
public static int PAGECOUNT; //²éѯºó·µ»ØµÄ×ÜÒ³Êý ÒòΪjavaµÄº¯Êý²»ÄÜ´«ÒýÓÃËùÒÔÐèÒªÓþ²Ì¬±äÁ¿À´»ñµÃ
public DataBean()
{
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/MyData", "root","loikenu");
context = new InitialContext();
datasource = (DataSource)context.lookup("jdbc/MyData");
conn = datasource.getConnection();
//stmt =conn.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public UserBean checkUsersLogin(String userName, String userPwd) //µÇ½ÑéÖ¤
{
UserBean ub = null;
if (!checkParameter(userName + userPwd))
{
userName = "null";
userPwd = "null";
}
try
{
String sql =
"select count(*) from admin where userName=? and userPwd=?";
prepar = conn.prepareStatement(sql);
//set parameter values for preparedstatment object
prepar.setString(1, userName);
prepar.setString(2, userPwd);
//execute query using preparedstatement object
res = prepar.executeQuery();
if (res.next())
{
//get data from reults set returned by jdbc
if (res.getInt(1) > 0)
{
ub = this.getUser(userName);
}
else
{
ub = null;
}
}
}
catch (Exception e)
{
ub = null;
e.printStackTrace();
}
return ub;
}
public UserBean getUser(String userName) //ÌáÈ¡µÇ½Óû§ÐÅÏ¢
{
UserBean ub = new UserBean();
int i=1;
String sql = "select * from admin where userName=?";
try
{
prepar = conn.prepareStatement(sql);
prepar.setString(1, userName);
res = prepar.executeQuery();
while (res.next())
{
ub.setUserName(res.getString("userName"));
ub.setUserPwd(res.getString("userPwd"));
ub.setUserId(i);
}
i++;
}
catch (SQLException ex)
{
ex.printStackTrace();
}
return ub;
}
public boolean checkParameter(String para) //¹ýÂË·Ç·¨×Ö·û
{
int flag = 0;
flag += para.indexOf("'") + 1;
flag += para.indexOf(";") + 1;
flag += para.indexOf("1=1") + 1;
flag += para.indexOf("|") + 1;
flag += para.indexOf("<") + 1;
flag += para.indexOf(">") + 1;
if (flag != 0)
{
System.out.println("Ìá½»ÁË·Ç·¨×Ö·û!!!");
return false;
}
return true;
}
public ArrayList selectCDBean(String selectValue, int page, int count) //²éѯ·ÖÒ³
{
ArrayList list = new ArrayList();
if (!checkParameter(selectValue))
{
selectValue = "";
}
try
{
proc = conn.prepareCall("{call proc_page(?,?,?,?)}");
proc.setInt(1, page);
proc.setInt(2, count);
proc.setString(3, selectValue);
proc.registerOutParameter(4, Types.INTEGER); //OUTPUT²ÎÊý ·µ»Ø½á¹¹¹²¶àÉÙÒ³
res = proc.executeQuery(); //½ÓÊÕ´æ´¢¹ý³ÌµÄ½á¹û¼¯
while (res.next()) //ÌáÈ¡½á¹û¼¯µÄÿÌõ¼Ç¼
{
CDBean cb = new CDBean();
cb.setCdAlbum(res.getString("CDalbum"));
cb.setCdCompany(res.getString("CDcompany"));
cb.setCdName(res.getString("CDname"));
cb.setCdId(res.getLong("CDid"));
cb.setCdType(getCDType(res.getInt("CDtypeId")));
list.add(cb);
}
PAGECOUNT = proc.getInt(4);
}
catch (SQLException ex)
{
ex.printStackTrace();
}
return list;
}
public String getCDType(int cdtypeId)
{
ResultSet res1=null;
try
{
java.sql.PreparedStatement prepar1 = conn.prepareStatement(
"select display from CDtype where CDtypeId=?");
prepar1.setLong(1, cdtypeId);
res1 = prepar1.executeQuery();
res1.next();
return res1.getString("display");
}
catch (SQLException ex)
{
return null;
}
}
public boolean setCDBean(CDBean cb)
{
if (!checkParameter(cb.getCdName() + cb.getCdCompany() + cb.getCdAlbum() +
cb.getCdType()))
{
return false;
}
boolean flag = false;
String sql =
"update CDinfo set CDname=?,CDcompany=?,CDalbum=?,CDtypeId=? where CDid=?";
try
{
prepar = conn.prepareStatement(sql);
prepar.setString(1, cb.getCdName());
prepar.setString(2, cb.getCdCompany());
prepar.setString(3, cb.getCdAlbum());
prepar.setInt(4, Integer.parseInt(cb.getCdType()));
// prepar.setLong(5, cb.getCdId());
int result = prepar.executeUpdate();
if (result > 0)
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception ex)
{
flag = false;
ex.printStackTrace();
}
return flag;
}
public CDBean getCDBean(long id)
{
CDBean cb = new CDBean();
int i=1;
String sql = "select * from CDinfo where CDid=?";
try
{
prepar = conn.prepareStatement(sql);
prepar.setLong(1, id);
res = prepar.executeQuery();
while (res.next())
{
cb.setCdAlbum(res.getString("CDalbum"));
cb.setCdCompany(res.getString("CDcompany"));
cb.setCdName(res.getString("CDname"));
cb.setCdId(i);
cb.setCdType(getCDType(res.getInt("CDtypeId")));
}
i++;
}
catch (SQLException ex)
{
ex.printStackTrace();
}
return cb;
}
public boolean deleteCDBean(long id)
{
boolean flag = false;
String sql = "delete from CDinfo where CDid=?";
try
{
prepar = conn.prepareStatement(sql);
prepar.setLong(1, id);
int result = prepar.executeUpdate();
if (result > 0)
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception ex)
{
flag = false;
ex.printStackTrace();
}
return flag;
}
public boolean addCDBean(CDBean cb)
{
boolean flag = false;
if (!checkParameter(cb.getCdName() + cb.getCdCompany() + cb.getCdAlbum() + cb.getCdId()+
cb.getCdType()))
{
return false;
}
String sql = "insert into CDinfo values(?,?,?,default,?)";
try
{
this.prepar = conn.prepareStatement(sql);
prepar.setString(1, cb.getCdName());
prepar.setString(2, cb.getCdCompany());
prepar.setString(3, cb.getCdAlbum());
prepar.setInt(4, Integer.parseInt(cb.getCdType()));
int result = prepar.executeUpdate();
if (result > 0)
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception ex)
{
flag = false;
ex.printStackTrace();
}
return flag;
}
public boolean setUserBean(UserBean ub)
{
boolean flag = false;
String sql = "update admin set userPwd=? where userId=?";
try
{
if (!checkParameter(ub.getUserPwd()))
{
return false;
}
this.prepar = conn.prepareStatement(sql);
prepar.setString(1, ub.getUserPwd());
prepar.setLong(2, ub.getUserId());
int result = prepar.executeUpdate();
if (result > 0)
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception ex)
{
flag = false;
ex.printStackTrace();
}
return flag;
}
public boolean addUserBean(UserBean ub)
{
boolean flag = false;
String sql = "insert into admin(userName,userPwd) values(?,?)";
//int i=1;
if (!checkParameter(ub.getUserPwd() + ub.getUserName()+ub.getUserId()))
{
return false;
}
if (hasUser(ub.getUserName()))
{
return false;
}
try
{
prepar = conn.prepareStatement(sql,prepar.RETURN_GENERATED_KEYS);
prepar.setString(1, ub.getUserName());
prepar.setString(2, ub.getUserPwd());
// prepar.setLong(3,ub.getUserId());
int result = prepar.executeUpdate();
if (result > 0)
{
flag = true;
}
else
{
flag = false;
}
// i++;
}
catch (Exception ex)
{
flag = false;
ex.printStackTrace();
}
return flag;
}
public boolean hasUser(String userName)
{
boolean flag = true;
String sql = "select count(*) from admin where userName=?";
try
{
prepar = conn.prepareStatement(sql);
prepar.setString(1, userName);
res = prepar.executeQuery();
res.next();
int result = res.getInt(1);
if (result > 0)
{
flag = true;
}
else
{
flag = false;
}
}
catch (SQLException ex)
{
ex.printStackTrace();
flag = true;
}
return flag;
}
}
公共类数据库{
专用连接conn=null;
私有结果集res=null;
私人语境;
私有数据源;
私有语句stmt=null;
private java.sql.PreparedStatement prepar=null;
private java.sql.CallableStatement proc=null;
公共静态页面计数
公共数据库()
{
试一试{
Class.forName(“com.mysql.jdbc.Driver”);
conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/MyData“根”、“根”、“loikenu”);
context=新的InitialContext();
datasource=(datasource)context.lookup(“jdbc/MyData”);
conn=datasource.getConnection();
//stmt=conn.createStatement();
}捕获(例外e){
showMessageDialog(null,e.getMessage());
}
}
public UserBean checkUsersLogin(字符串userName,字符串userPwd)//
{
UserBean ub=null;
如果(!checkParameter(用户名+用户密码))
{
userName=“null”;
userPwd=“null”;
}
尝试
{
字符串sql=
“从管理员中选择count(*),其中userName=?和userPwd=?”;
prepar=conn.prepareStatement(sql);
//为preparedstatment对象设置参数值
准备设置字符串(1,用户名);
准备设置管柱(2,用户PWD);
//使用preparedstatement对象执行查询
res=prepar.executeQuery();
if(res.next())
{
//从jdbc返回的reults集合获取数据
如果(res.getInt(1)>0)
{
ub=这个.getUser(用户名);
}
其他的
{
ub=null;
}
}
}
捕获(例外e)
{
ub=null;
e、 printStackTrace();
}
返回ub;
}
公共用户bean getUser(字符串用户名)//
{
UserBean ub=newuserbean();
int i=1;
String sql=“select*from admin,其中userName=?”;
尝试
{
prepar=conn.prepareStatement(sql);
准备设置字符串(1,用户名);
res=prepar.executeQuery();
while(res.next())
{
ub.setUserName(res.getString(“用户名”));
ub.setUserPwd(res.getString(“userPwd”);
ub.setUserId(i);
}
i++;
}
catch(SQLException-ex)
{
例如printStackTrace();
}
返回ub;
}
公共布尔校验参数(字符串段)//
{
int标志=0;
标志+=段落索引(“”)+1;
标志+=段落索引(“;”)+1;
标志+=段落索引(“1=1”)+1;
标志+=段落索引(“|”)+1;
标志+=段落索引(“”+1);
如果(标志!=0)
{
System.out.println(“Ìá½»ÁÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ;
返回false;
}
返回true;
}
公共数组列表selectCDBean(字符串selectValue,int page,int count)//
{
ArrayList=新建ArrayList();
如果(!checkParameter(selectValue))
{
selectValue=“”;
}
尝试
{
proc=conn.prepareCall({callproc_page(?,,,?)});
程序设置(第1页);
过程设置(2,计数);
过程设置字符串(3,选择值);
过程寄存器输出参数(4,类型.整数);//输出
res=proc.executery();//½ÓÊÕÕææýÌĽý¼
while(res.next())//
{
CDBean cb=新的CDBean();
cb.setCdAlbum(res.getString(“CDalbum”);
cb.setCdCompany(res.getString(“CDcompany”);
cb.setCdName(res.getString(“CDname”);
cb.setCdId(res.getLong(“CDid”);
cb.setCdType(getCDType(res.getInt(“CDtypeId”));
列表。添加(cb);
}
PAGECOUNT=proc.getInt(4);
}
catch(SQLException-ex)
{
例如printStackTrace();
}
退货清单;
}
公共字符串getCDType(int-cdtypeId)
{
ResultSet res1=null;
尝试
{
java.sql.PreparedStatement prepar1=conn.prepareStatement(
“从CDtype中选择显示,其中CDtypeId=?”;
prepare1.setLong(1,cdtypeId);
res1=prepar1.executeQuery();
res1.next();
返回res1.getString(“显示”);
}
catch(SQLException-ex)
{
返回null;
}
}
公共布尔集合CDBean(CDBean cb)
{
如果(!checkParameter(cb.getCdName()+cb.getCdCompany()+cb.getCdAlbum())+
cb.getCdType())
{
返回false;
}
布尔标志=假;
字符串sql=
“更新CDinfo集CDname=?,CDcompany=?,CDalbum=?,CDtypeId=?其中CDid=?”;
尝试
{
prepar=conn.prepareStatement(sql);
prepar.setString(1,cb.getCdName());
prepare.setString(2,cb.getCdCompany());
prepar.setString(3,cb.getCdAlbum());
public class DataBean{
private Connection conn = null;
private ResultSet res = null;
// ...
private Statement stmt=null;
private java.sql.PreparedStatement prepar = null;
private java.sql.CallableStatement proc = null;
// ...
public UserBean getUser(String userName) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
// ...
public UserBean getUser(String userName) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
UserBean userBean = null;
String sql = "select userId, userName, userPwd from admin where userName = ?";
try {
connection = dataSource.getConnection();
statement = connection.prepareStatement(sql);
statement.setString(1, userName);
resultSet = statement.executeQuery();
if (resultSet.next()) {
userBean = new UserBean();
userBean.setUserId(resultSet.getInt("userId");
userBean.setUserName(resultSet.getString("userName"));
userBean.setUserPwd(resultSet.getString("userPwd"));
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return userBean;
}
try (Connection con = // get connection... ;
PreparedStatement ps = // create prepared statement... ;
ResultSet rs = ps.executeQuery()) {
// Process the result set...
// The AutoCloseable resources 'conn', 'ps', and 'rs' will be cleaned up at the end:
// .close() will be called on all of them whether an exception occurs or not
} catch (SQLException e) {
// TODO(mykey): Do not swallow me!!
}