关于com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
意思很明显:连接已经关闭,无法再访问数据库
具体原因我还说不清楚(有人说是因为静态方法获取连接引起的),DBUtil的代码是这样的:
public class DBUtil {
private static final String driver = "com.mysql.jdbc.Driver";// 数据库驱动
private static final String url = "jdbc:mysql://localhost:3306/myproject01?useUnicode=true&characterEncoding=UTF-8";// 连接数据库的URL地址,同时设置字符集编码
private static final String username = "root";// 数据库的用户名
private static final String password = "root";// 数据库的密码
// 创建数据库连接对象
private static Connection conn = null;
// 静态代码块负责加载驱动
static {
try {
Class.forName(driver);// 加载驱动
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 单例模式返回数据库连接对象
public static Connection getConnection() throws Exception {
if (conn == null) {
conn = DriverManager.getConnection(url, username, password);
return conn;
}
return conn;
}
}
我的解决办法是这样的:
try {
conn = DBUtil.getConnection();
psmt = conn.prepareStatement(sql);
psmt.setString(1, eName);
psmt.setString(2, ePassword);
rs = psmt.executeQuery();
while (rs.next()) {
employee.seteId(rs.getInt("e_id"));
employee.seteName(rs.getString("e_name"));
employee.seteSex(rs.getString("e_sex"));
employee.seteBirthday(rs.getDate("e_birthday"));
employee.setePhone(rs.getString("e_phone"));
employee.setePlace(rs.getString("e_place"));
employee.setePassword(rs.getString("e_password"));
employee.seteJoinTime(rs.getDate("e_jointime"));
employee.seteIsLead(rs.getBoolean("e_islead"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
// if (conn != null) {
// conn.close();
// }
if (psmt != null) {
psmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
不要关闭数据库连接,及把
// if (conn != null) {
// conn.close();
// }
去掉就可以了