有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

servlet中的java整数解析

这只是使用Employee ID在Employee数据库中的一个简单查询,其中ID是一个整数值。我执行了以下操作来解析integer中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>

共 (3) 个答案

  1. # 1 楼答案

    以下内容应该有效:

    String sqlStr = "select * from Employee where ID ="+id;
    

    您必须将id连接到您编写的查询字符串

    如注释中所述,最好使用参数化查询来防止sql注入

  2. # 2 楼答案

    问题是代码中没有使用id变量。这是一个文本字符串:

    "select * from Employee where ID = id "
                                       ^ here id is part of the string, it's not the id variable
    

    最简单的方法是将变量连接到字符串

    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层

    更多信息:

  3. # 3 楼答案

    改变

    String sqlStr = "select * from Employee where ID = id ";
    

    String sqlStr = "select * from Employee where ID = "+ id ;
    

    但是,您应该阅读一些关于SQL Injection