2014-09-08 2 views
-1

이것은 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

질문에서 오류가 무엇입니까? 하나는 중단 점이고 다른 하나는 경고입니다. 질문에 어떤 오류도 찾을 수 없습니다. – msrd0

+0

@ msrd0 문제는 OP가이 'id'변수를 사용하고 싶어하지만 필요가 없다는 것입니다. –

답변

2

문제는 코드에서 id 변수를 사용하지 않을 것입니다. 이 작품은 문자열

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

그러나 동적 쿼리를 만들 수있는 올바른 방법으로하지 않습니다에 변수을 연결 될 수 있도록

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

순진 방법 :이 리터럴 문자열입니다. 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

변경

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

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

그러나, 당신은 일을해야 뭔가 다음에 대한 SQL Injection

+2

이것은 기술적으로 사실이지만 올바른 방법은 아닙니다. –

+0

SQL 삽입뿐만 아니라 코드 유지 관리 및 SQL 문 실행 성능. –

0

을 읽어야 할 사람 :

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

당신은 당신이 쓴 쿼리 문자열에 ID를 연결하는 있습니다.

주석에서 언급 한대로 편집하십시오. SQL injection을 방지하기 위해 매개 변수화 된 쿼리를 사용하는 것이 좋습니다.

+1

@Andres의 대답과 비슷하지만 기술적으로는 사실이지만 올바른 방법은 아닙니다. –