这只是使用Employee ID在Employee数据库中的简单查询,其中ID是整数值。我做了以下操作来解析整数ID的值。
String value = request.getParameter("Employee_ID");
int id = Integer.parseInt(value);
// Step 3: Execute a SQL SELECT query
String sqlStr = "select * from Employee where ID = id ";
但是它给了我以下错误:
Multiple markers at this line
- Line breakpoint:QueryServlet [line: 45] - doGet(HttpServletRequest,
HttpServletResponse)
- The value of the local variable id is not used
我的html文件:
<html>
<head>
<title>Employee Details</title>
</head>
<body>
<h2>Employee Details</h2>
<form method="get" action="http://localhost:9999/abcd/query">
<b>Select Employee ID:</b>
<input type="text" name="Employee_ID" value="ex101">
<input type="submit" value="Search">
</form>
</body>
</html>
答案 0 :(得分:2)
问题是您没有在代码中使用id
变量。这是一个文字字符串:
"select * from Employee where ID = id "
^ here id is part of the string, it's not the id variable
实现这项工作的天真方法是将变量连接到String
String sqlStr = "select * from Employee where ID = " + id;
但这不是创建动态查询的正确方法。您应该使用PreparedStatement
并相应地传递参数。这就是代码的样子:
//placeholder for id variable
String sqlStr = "select * from Employee where ID = ?";
//retrieve the connection to database
Connection con = ...;
//prepare the statement from the connection
PreparedStatement pstmt = con.prepareStatement(sqlStr);
//pass the id as parameter to the prepared statement
pstmt.setInt(id);
//execute the statement
ResultSet rs = pstmt.execute();
此外,请确保将代码拆分为多个层。所有与数据库连接和SQL执行相关的代码都属于DAO层。
更多信息:
答案 1 :(得分:1)
更改
String sqlStr = "select * from Employee where ID = id ";
通过
String sqlStr = "select * from Employee where ID = "+ id ;
但是,您应该阅读有关SQL Injection
的内容答案 2 :(得分:0)
下面应该有效:
String sqlStr = "select * from Employee where ID ="+id;
您必须将id连接到您编写的查询字符串。
如注释中所述编辑,最好使用参数化查询来防止sql注入。