2017-05-21 7 views
0

이 코드가 SQL 예외를 throw하는 이유를 파악하려고합니다. 이 코드를 실행하면 내부 catch 블록의 메시지 인 "고객 삽입 ps의 잘못된 SQL"이 인쇄됩니다. 나는이 클래스와 다른 곳에서 이처럼 SQL 인서트를 여러개 준비된 문장으로 가지고있다. 모두 잘 작동합니다. 나는이 것을 반복해서 살펴 보았는데 왜 이것이 예외를 던지고 있는지 알 수 없다. 당신이 Statement를 사용하는 것처럼Prepared Statement의 SQL에서 SQL 예외 발생

try { 
       Connection conn = DBconnection.getConnection(); 
       PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";"); 
       System.out.println(ps.toString()); 
       ResultSet rs = ps.executeQuery(); 

       if (rs.next()) { 
        customerId = rs.getString("customerId"); 
       } 
       try { 

        PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT " 
          + "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" 
          + "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");"); 

        customerInsert.executeUpdate(); 

        System.out.println(customerInsert.toString()); 
        System.out.println(rs.toString()); 

       } catch (SQLException sq) { 
       System.out.println("Bad SQL in customer insert ps"); 
       } 

      } catch (SQLException customerIdException) { 
       System.out.println("Bad SQL in customer ps"); 
      } 

답변

1

당신은 PreparedStatement을 사용하고 있습니다. SQL에 매개 변수를 넣지 마십시오. 자리 표시 자 ? 표시를 넣으십시오. 그런 다음 매개 변수를 채우기 위해 다양한 setXyz 방법 (setString, setInt 등)를 사용 : 나는 그것을 시도거야

PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
    "INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" + 
        "VALUES(?, ?, ?, ?, ?, ?, ?);" 
); 
customerInsert.setString(1, name); 
customerInsert.setInt(2, addressId); 
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect 
+0

. 나는이 클래스와 비슷한 다른 문장을 내 수업 및 프로그램에서 작동하도록 설정되어 있습니다. 근본적인 문제가 여기에 무엇인지 확실하지 않습니다. 이 작업을 수행하면 문제가 해결되고 행복 할 것이고 체크 표시를 클릭하겠습니다. 고맙습니다! 나는 StackOverflow에 다소 새로운 것이다. – aforbe2

+0

@ aforbe2 : 걱정할 필요없고 서두를 필요가 없습니다. 질문에 표시 한 양식의 다른 사용자가있는 경우에도 작업 중이 라해도 위 양식을 사용하도록 업데이트하는 것이 중요합니다. 문제의 코드가 작성된 방식은 ** 와이드 ** SQL 주입 공격. 우리 중 누구도이 전화를하고 싶지 않습니다. http://bobby-tables.com :-) –

+1

하하, 만화책을 가져 주셔서 감사합니다. 나는 이것을 명심해야한다. 또한 친절 하심에 감사드립니다. 나는 약간의 devs가 거의 가시가 없다는 것을 알았다. 내가 왜 예외를 던지게되었는지 모르겠지만 당신의 대답이 내 문제를 고쳤고, 다른 모든 문장을 set 메소드를 사용하도록 바꾸고 있습니다. – aforbe2