When Java deals with database (Mysql), an error often occurs: No operations allowed after connection closed. Literally, no operations are allowed after connection is closed.
Problem description: In a small project of struts2, you want to delete the photos uploaded by the user before. Uploading photos is by uploading them to the database picture table (id, uid, name, url, where uid is the user id, which is automatically grown) related information about the photos (no photos themselves stored); and storing the photos themselves on the server (copy). Therefore, when deleting the database, you must delete these two aspects.
Delete information in the database: directly call DAO method in Action to delete records of photos in the database
Delete the photo files stored on the server: In fact, it is to find the directory where the photo files are stored and delete the photo files. Here you need to get the absolute path (the relative path passed in when uploading the photo). Relative paths can be written in DAO to a URL (relative path) based on the id value sent from the front end, and this method in DAO is called in Action.
The code that has problems:
//Delete photos
public String deletepic()
{
//How to delete the photo files uploaded by the server side
String path=(());//The first time I call the method in dao
//Get the application object to get the absolute path
ServletContext application= ();
path=("")+path;
//Embroider into a File file, and then call the method in FileUtils to delete the file
File myFile=new File(path);
(myFile);
// Method of deleting records in the database
(());//The second call to the method in DAO
return null;
}
reason: Because there are two things to do in this deletepic method: (Two calls to the method in dao)
(1) Delete the information records about photos in the database. To call the deletepic method in DAO, the conn in the method has been closed at this time.
(2) Delete the photo file saved in the server. To call the getURl method in DAO, the conn is not re-getable at this time, so an error is reported.
solve: This requires us to pay attention to the standardization of the code when writing methods in the database. Generally, each method must first determine whether the shared database connection is closed conn if(())
{
conn=();
}
Then close the database connection at the end of the method ();
Example: Methods in DAO delete records in database based on id value
//1. Methods to delete photos recorded in the database
public void deletepicture(int id)
{
try {
if(())
{
conn=();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
();
}
sql="delete from pictures where id=?";
try {
ps= (sql);
(1, id);
();
();
} catch (SQLException e) {
// TODO Auto-generated catch block
();
}
}