一个常见的JDBC封装导致的问题
大家看一个数据库封装类 操作一次没问题,操作两次就报错 com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
Debug调试,发现connection不能真正关掉,使用connection完后,调用close()方法,下次getConnection()时候 instance不为null
public class ConnectionUtil {
private final static String url="jdbc:mysql://localhost:3306/qq?useUnicode=true&characterEncoding=UTF-8";
private final static String username="root";
private final static String password="root";
private static Connection instance=null;
private ConnectionUtil(){
if(instance==null){
try {
Class.forName("org.gjt.mm.mysql.Driver");
instance=DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static Connection getConnection(){
if(instance==null){
new ConnectionUtil();
}
return instance;
}
public static void close(Connection con,PreparedStatement ps,ResultSet rs){
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
con=null;
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps=null;
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs=null;
}
}
}
public static void close(Connection con,PreparedStatement ps){
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
con=null;
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps=null;
}
}
}
public static void close(Connection con){
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
con=null;
}
}
}
}
结贴了。。。。有其他结贴方式吗?
朋友很热心,但是你却没有明白Java的基本数据类型与引用类型的区别。 你这样会对人造成误导的,不是楼主搞错了而是你搞错了。
楼主的代码写得确实很混乱。
这个单列写的。。。。。。。我看着似乎不敢发言了。
没发现搂主 instance=null 的语句
+1 new ConnectionUtil 匿名对象
连同步都没有,还能出来死锁....
instance 和 con 是一个对象的两个引用,假设对象为A, B和C为到A的引用,C=null只是切断了C到A的联系,B与A的联系依然存在。
非常常用的功能,建议先找找有没通用的开源实现 http://commons.apache.org/dbutils/
正解,Java的参数都是值传递,非引用传递
你这个单例写的,有可能产生死锁
1 单例模式 应用错误 2 由于单例使用错误 多次getconnection都是同一连接 调用一次close 其他地方持有的连接全部报废... 3 关闭连接时候并不判断是不是本池所产生的 就乱关闭 这样关闭了连接并未多对象池的连接造成任何影响. 剩下的就是 次要错误了, 解决了这三个其他的自然就没有错误了..
哥们你还真没说到点子上,这个是由于咋们java基础不好,建议你看看前面的帖子
哎,这代码写的。第一个的close的关闭顺序就有问题。 第二个,你在返回后再传入的Connection已经不是ConnectionUtil类中那个类变量了。 不会影响instance的。所以拿到的永远是同个一个Connection. 再说了instance是个类变量。只要它有值了,所有实例是共有的。
哎,杯具呀。
new对象只是为了调用构造方法时候,给instance赋值,我还是没太明白你的意思
new的对象没引用,就成了逃逸对象,这就是你debug到instance存在,而connection closed(就是我刚刚说的女娲)的原因。而且你这个所谓的单例也写的。。。。