连接MYSQL的一个javaBean出错

simplemanNO1 2004-09-19 06:08:17
package note;
import java.sql.*;

public class Jdbc_conn{
String sDBDriver="com.mysql.jdbc.Driver";
String sConnStr="jdbc:mysql://localhost:3306/sample_db?user=root&password=root";
Connection conn=null;
ResultSet rs=null;

public Jdbc_conn(){
try
{
Class.forName(sDBDriver);
}
catch(ClassNotFoundException e)
{

System.out.println("Jdbc_conn():"+e.getMessage());
}
}

public void executeUpdate(String sql)throws Exception{
sql=new String(sql.getBytes("GBK"),"ISO8859_1"); //设置编码格式
try{
conn=DriverManager.getConnection(sConnStr);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(sql);
stmt.close();
conn.close();

}
catch(SQLException ex){
System.out.println("sql.executeUpdate:"+ex.getMessage());
}
}
public ResultSet executeQuery(String sql)throws Exception{
rs=null;
try{
sql=new String(sql.getBytes("GBK"),"ISO8859_1"); //编码设置
conn=DriverManager.getConnection(sConnStr);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs=stmt.executeQuery(sql);
stmt.close();
conn.close();

}
catch(SQLException ex){
System.out.println("sql.executeQuery:"+ex.getMessage());
}
return rs;
}

*******************************************
我把二个方法中的stmt.close();conn.close();去掉就可以了,但是我觉得不应该去掉呀,就这样到底错在那里了?请高人指点!
...全文
76 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangwei8117 2004-09-20
  • 打赏
  • 举报
回复
当然要去掉stmt.close();conn.close();了,因为你要返回记录集,要是关闭的话怎么返回啊,可以在连接前先判断一下是否已经关闭,用if(rs==null){rs.close();stmt.close();conn.close();}
这样就可以了!
Acylas 2004-09-20
  • 打赏
  • 举报
回复
还有下面这种写法是由问题的,假如你的sql语句是有问题不能正常运行的,那么你的conn就不能被正常释放,应该将stmt.close();conn.close();从try里面拿出来,放到finally里面去
try{
conn=DriverManager.getConnection(sConnStr);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(sql);
stmt.close();
conn.close();

}
catch(SQLException ex){
System.out.println("sql.executeUpdate:"+ex.getMessage());
}
try {
......
}
catch ....
finally {
try {
stmt.close();
}
......
}
Acylas 2004-09-20
  • 打赏
  • 举报
回复
是要去掉的,resultset要靠connection维持,你关闭掉conn,resultset也就断掉了
simplemanNO1 2004-09-20
  • 打赏
  • 举报
回复
难道没有一个人为我解难?是我的帖子太长了吗?其实很简单啊,请高手指点!

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧