2015-02-06 3 views
0

이것은 내 코드입니다. 나는 처리를 위해 사용하는 MySQL DB를 가지고있다. 나는이 예외와 관련된 모든 질문을 언급했다. 그러나 그들 중 누구도 나를 위해 일을하지 않았습니다. 문제는 내가 사용한 쿼리 때문입니다. 쿼리를 만들 때JDBC MySQL이 SQL 실패를 실행합니다.

SELECT * FROM customers; 

다음과 같이하면됩니다. 하지만이를 다음과 같이 업데이트하면 예외가 발생합니다.

SELECT * FROM customer WHERE customer_id LIKE " + "'%" + consumerId + "%' 

이것은 예외입니다. 귀하의 요청이 너무 오래 걸립니다 내 이론이 사실이라면

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) 
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1036) 
    at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:627) 
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1013) 
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234) 
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265) 
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064) 
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790) 
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) 
    at sun.reflect.GeneratedConstructorAccessor4.newInstance(Unknown Source) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) 
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395) 
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325) 
    at java.sql.DriverManager.getConnection(DriverManager.java:571) 
    at java.sql.DriverManager.getConnection(DriverManager.java:215) 
    at com.smart.data.customer.CustomerInfoProvider.findDetails(CustomerInfoProvider.java:81) 
    at com.smart.data.customer.CustomerInfoProvider.provideRequiredCustomerDetails(CustomerInfoProvider.java:28) 
    at com.smart.data.manipulator.Starter.main(Starter.java:36) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:606) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost. 
    at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2914) 
    at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:559) 
    ... 22 more 
Exception in thread "main" java.lang.NullPointerException 
    at com.smart.data.customer.CustomerInfoProvider.provideRequiredCustomerDetails(CustomerInfoProvider.java:30) 
    at com.smart.data.manipulator.Starter.main(Starter.java:36) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:606) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 
package com.smart.data.customer; 

import org.apache.log4j.Logger; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.sql.*; 
import java.util.ArrayList; 
import java.util.Properties; 

/** 
* Created with IntelliJ IDEA. 
* User: dulithdecozta 
* Date: 2/5/15 
* Time: 7:20 PM 
* To change this template use File | Settings | File Templates. 
*/ 
public class CustomerInfoProvider { 
    static Logger log = Logger.getLogger(CustomerInfoProvider.class.getName()); 
    ResultSet customerResultSet = null; 
    Connection conn = null; 

    public void provideRequiredCustomerDetails(ArrayList customerIdArraylist) { 
     for (int i = 0; i < customerIdArraylist.size(); i++) { 
      try { 
       customerResultSet = findDetails(customerIdArraylist.get(i).toString()); 
       try { 
        while (customerResultSet.next()) { 
         try { 
          System.out.println("Fullname : " + customerResultSet.getString("fullname")); 
          System.out.println("Consumer ID : " + customerResultSet.getString("customer_id")); 
          System.out.println("City : " + customerResultSet.getString("city")); 
          System.out.println("gender : " + customerResultSet.getString("gender")); 
          System.out.println("Occupation : " + customerResultSet.getString("occupation")); 
          System.out.println(i); 
          System.out.println("*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*"); 
         } catch (SQLException e) { 
          e.printStackTrace(); 
         } 
        } 
       } catch (SQLException e) { 
        e.printStackTrace(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     try { 
      conn.close(); 
     } catch (SQLException e) { 
      e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
     } 
    } 

    public ResultSet findDetails(String consumerId) throws IOException { 
     // Load property file 
     Properties properties = new Properties(); 
     // Define an input stream 
     InputStream inputStream = null; 
     ResultSet rs = null; 
     try { 
      inputStream = new FileInputStream("/home/abc/Desktop/Jigi/database.properties"); // Path to the property file 
     } catch (FileNotFoundException e) { 
      log.debug("Exception encountered : File Not Found : "); 
      e.printStackTrace(); 
     } 
     try { 
      // load a properties file 
      properties.load(inputStream); 
     } catch (IOException e) { 
      log.debug("Exception encountered : A problem with the Input Stream : "); 
      e.printStackTrace(); 
     } 
     conn = null; 
     Statement stmt = null; 
     try { 
      Class.forName(properties.getProperty("JDBC_DRIVER")); 
      // log.debug("Connecting to database...!!"); 
      conn = DriverManager.getConnection(properties.getProperty("DB_URL"), properties.getProperty("USER"), properties.getProperty("PASS")); 
      // log.debug("Creating statement...!"); 
      stmt = conn.createStatement(); 
      rs = stmt.executeQuery("SELECT * FROM customer WHERE customer_id LIKE " + "'%" + consumerId + "%'"); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 

     return rs; 
    } 
} 
+0

질문에 예외도 넣으십시오 –

+0

done @AmirHosseinMehrvarzi –

+0

귀하의 MySQL 버전과 호환되는 드라이버 버전입니까? –

답변

0

쿼리를 변경하면 예외가 발생하지 않고 결과가 반환됩니다.

package com.smart.data.customer; 

import org.apache.log4j.Logger; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.sql.*; 
import java.util.ArrayList; 
import java.util.Properties; 

/** 
* Created with IntelliJ IDEA. 
* User: dulithdecozta 
* Date: 2/5/15 
* Time: 7:20 PM 
* To change this template use File | Settings | File Templates. 
*/ 
public class CustomerInfoProvider { 
    static Logger log = Logger.getLogger(CustomerInfoProvider.class.getName()); 
    ResultSet customerResultSet = null; 
    Connection conn = null; 

    public void provideRequiredCustomerDetails(ArrayList customerIdArraylist) { 
     for (int i = 0; i < customerIdArraylist.size(); i++) { 
      try { 
       customerResultSet = findDetails(customerIdArraylist.get(i).toString()); 
       try { 
        while (customerResultSet.next()) { 
         try { 
          System.out.println("Fullname : " + customerResultSet.getString("fullname")); 
          System.out.println("Consumer ID : " + customerResultSet.getString("customer_id")); 
          System.out.println("City : " + customerResultSet.getString("city")); 
          System.out.println("gender : " + customerResultSet.getString("gender")); 
          System.out.println("Occupation : " + customerResultSet.getString("occupation")); 
          System.out.println(i); 
          System.out.println("*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*"); 
         } catch (SQLException e) { 
          e.printStackTrace(); 
         } 
        } 
       } catch (SQLException e) { 
        e.printStackTrace(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     try { 
      conn.close(); 
     } catch (SQLException e) { 
      e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
     } 
    } 

    public ResultSet findDetails(String consumerId) throws IOException { 
     // Load property file 
     Properties properties = new Properties(); 
     // Define an input stream 
     InputStream inputStream = null; 
     ResultSet rs = null; 
     try { 
      inputStream = new FileInputStream("/home/abc/Desktop/Jigi/database.properties"); // Path to the property file 
     } catch (FileNotFoundException e) { 
      log.debug("Exception encountered : File Not Found : "); 
      e.printStackTrace(); 
     } 
     try { 
      // load a properties file 
      properties.load(inputStream); 
     } catch (IOException e) { 
      log.debug("Exception encountered : A problem with the Input Stream : "); 
      e.printStackTrace(); 
     } 
     conn = null; 
     Statement stmt = null; 
     try { 
      Class.forName(properties.getProperty("JDBC_DRIVER")); 
      // log.debug("Connecting to database...!!"); 
      conn = DriverManager.getConnection(properties.getProperty("DB_URL"), properties.getProperty("USER"), properties.getProperty("PASS")); 
      // log.debug("Creating statement...!"); 
      stmt = conn.createStatement(); 
      rs = stmt.executeQuery("SELECT * FROM customer WHERE customer_id=" +consumerId); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 

     return rs; 
    } 
} 
2

는, 당신은 쿼리를 어떻게 든 적은 시간을 확인해야합니다. 당신이 LIKE 절에 선두 %를 생략하면

당신은 당신은 MySQL이 올바른 행을 찾기 위해 인덱스를 사용할 수 있도록,

SELECT col1, col2, col3 
    FROM customer 
    WHERE customer_id LIKE '" + consumerId + "%'" 
    LIMIT 10 

을 시도 할 수 있습니다.

쿼리에서 필요한 열을 열거 할 때 네트워크 트래픽을 줄이고 MySQL이 쿼리에 대한 응답을 구성하는 데 몇 가지 효율성을 사용할 수 있습니다.

LIMIT 10라고 말하면 사용자가 실수로 빈 문자열을 요청하면 MySQL이 전체 테이블을 반환 할 가능성을 피할 수 있습니다.

또한 customerId 값에 대한 바인드 매개 변수를 사용해야합니다. JDBC를 사용하여이를 수행하는 방법을 찾을 수 있습니다.

+0

예. 확인했습니다. 감사합니다. 하지만 여전히 작동하지 않습니다. 귀하의 절차에서 이전보다 훨씬 많은 데이터가 표시되었습니다. 그러나 여전히 언젠가 예외가 발생합니다. 어쨌든 원인은 정확합니다. –

1

이러한 데이터를 배열 목록에 저장하고 필요할 때 해당 목록을 호출 할 수 있습니다. 이 예외를 방지하는 데 도움이됩니다. 이는 쿼리의 응답 시간이 짧기 때문입니다.