[英]Cannot delete a record in JDBC
您好,我正在嘗試為學校項目創建一些頁面。 整個主題是關於創建,刪除,搜索,更新度假目的地。 我在刪除記錄時遇到問題。 我創建了一個帶有表單的html頁面,以便接收要刪除的目的地的名稱。 接下來是我創建的Java頁面的代碼。 你有什么不對嗎? 因為無論我嘗試什么記錄都不會被刪除。 謝謝
HTML頁面
<html>
<head>
<title>Delete</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1 align="center">Insert the destination you want to delete</h1>
<form action="delete.jsp" method="post">
<input type="text" name="delete">
<BR>
<INPUT TYPE="SUBMIT" value="Delete!">
</form>
</body>
</html>
Java頁面:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Delete</title>
</head>
<body>
<%
String name=request.getParameter("name");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vac",
"user","pass");
Statement myStatement=con.createStatement();
String SQLstring="DELETE FROM dest WHERE name= '" +name+ "'";
myStatement.executeUpdate(SQLstring);
myStatement.close();
con.close();
out.println("Destination deleted!");
%>
</body>
</html>
我認為根據表單輸入名稱,參數名稱是“刪除”,沒有“名稱”。
問候。
正如Antonio Martinez的回答所指出的,參數名稱不正確(不是name
而是delete
)。 我覺得我必須發布此答案以指出您的代碼顯示的SQL注入風險。
您永遠不要以自己的方式構建查詢(使用外部參數構建語句),因為它可以允許注入惡意代碼。 您應該始終使用准備好的語句來處理用戶的輸入:
String sqlString = "delete from dest where name=?";
/* The question-mark is a place holder for the parameter.
Notice that you don't need to enclose it in quotes,
the prepared statement will take care about that. */
PreparedStatement ps = con.prepareStatement(sqlString);
/* Notice that nothing is executed here: you're only preparing the
statement using the SQL string (which includes the place-holder(s)
for the parameter(s). */
ps.setString(1, delete)
/* Here you assign the parameter(s) value(s) to the prepared statement.
The parameters are numbered starting from one, and ordered
the way they appear in your SQL string.
The setXXX() methods of the prepared statement allow you to
pass the correct value to the query. Strings, in this case, are
properly handled, so any rogue code the user might try to inject will
not pass as "executable code", but simply as a string. */
ps.execute();
同樣,我建議您在這里閱讀有關SQL注入攻擊的知識:它們是什么,它們帶來的風險是什么以及如何防止它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.