我有一个删除相册DAO,一个删除相册类和一个删除servlet都连接到数据库,但它仍然没有运行查询,即它没有工作。
以下代码用于删除servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
DeleteAlbum Album = new DeleteAlbum(name) ;
AlbumDAO.INSTANCE.delete(Album);
request.getRequestDispatcher("home.jsp").forward(request, response);
}
这是删除专辑类
public class DeleteAlbum {
String name ;
public DeleteAlbum(String name){
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这部分代码连接到数据库
public enum DeleteAlbumDAO {
INSTANCE;
public Connection getConnection() {
Connection con = null ;
try {
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/oneDB", "sa", "");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con ;
}
public void delete(Album name) {
try {
Connection con = getConnection() ;
Statement stmt = con.createStatement();
stmt.executeUpdate("Delete from ALBUM WHERE name="+name+"");
System.out.println("Connection Succesful");
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
这是原始ALBUM DAO的代码,我试图按名称删除相册,我添加了albumDAO以测试ti是否已连接但仍然无法正常工作
import model.Album;
import model.DeleteAlbum;
public enum AlbumDAO {
INSTANCE;
public Connection getConnection() {
Connection con = null ;
try {
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/oneDB", "sa", "");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con ;
}
public void save(Album album) {
try {
Connection con = getConnection() ;
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO ALBUM (name, artist , genre)"
+ "VALUES ('" + album.getName() + "','"+ album.getArtist() + "','"+ album.getGenre() + "')");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void delete(DeleteAlbum name) {
try {
Connection con = getConnection() ;
Statement stmt = con.createStatement();
stmt.executeUpdate("Delete from ALBUM WHERE name="+name+"");
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您实际上并未将alubum名称传递给预准备语句,因此您需要更改delete
方法,如下所示:
public void delete(DeleteAlbum album) {
//Use try with resources as shown below which closes conn & stmt objects
try(Connection con = getConnection() ;
PreparedStatement stmt = con.prepareStatement("Delete from ALBUM WHERE name=?")) {
stmt.setString(1, album.getName());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
请使用preparedstament setString(),setInt()等方法以避免SQL injections。您可以参考here
另外,请确保使用try with resources或关闭finally块中的资源,以避免连接泄漏。