2013-11-25 2 views
0

인터넷 검색이 끝난 후 나는 마침내 모든 강력한 SO 커뮤니티에 물어볼 시간을 결정했습니다. MySQL 데이터베이스에 이미지를 삽입하거나 업데이트하려고합니다. 다음과 같이 내가 사용하고 쿼리 및 코드는 다음과 같습니다Java에서 Java로 BLOB 삽입/업데이트

FileInputStream inputStream = new FileInputStream(file); 

    String[] str_array = file.getName().split("-"); 
    String stringb = str_array[1]; 
    String stringc = str_array[2]; 
    String fingerName = stringc.substring(0, 2); 
    //gets file name and splits it accordingly 

    String id = getID.id(stringb); //does a sql lookup to get the previously inserted id according to the stringb(users unique id number) 

    String INSERT_PIC = "INSERT INTO database.user_picture(id_ref, picture_num, user_image) values('" + id + "', ?, ?) ON DUPLICATE KEY UPDATE user_image = ?;"; 

    //creates the sql statement that inserts or updates according to the primary keys id_ref and picture_num 

    ps = (PreparedStatement) connection.prepareStatement(INSERT_PIC); 

    ps.setString(1, fingerName); 
    ps.setBinaryStream(2, (InputStream) inputStream, file.length()); 
    ps.setBinaryStream(3, (InputStream) inputStream, file.length()); 

    //creates the prepared statement and inserts the 3 parameters 

    ps.executeUpdate(); 
    connection.commit(); 
    //executes the query on the connected database 

내가이 일 것이라고 확신했다. 테스트 할 때 이미지를 데이터베이스에 올바르게 삽입합니다. 모든 필드를 업데이트 할 때 blob/image 필드를 제외하고 올바르게 업데이트됩니다. 대신 blob/image 필드가 NULL로 변경됩니다.

나는 이런 일이 나이 작업을 얻을 수있는 다른 방법으로, 어떤 제안이

답변

1

매개 변수 2와 3 모두에 대해 동일한 입력 스트림을 제공합니다. 문이 실행되면 매개 변수 2 스트림이 끝날 때까지 먼저 읽 힙니다. JDBC 드라이버가 매개 변수 3의 스트림을 읽으려고하면 동일한 스트림 인스턴스이므로 이미 끝났습니다.

또한
FileInputStream inputStream1 = new FileInputStream(file); 
FileInputStream inputStream2 = new FileInputStream(file); 
[...] 
ps.setBinaryStream(2, (InputStream) inputStream1, file.length()); 
ps.setBinaryStream(3, (InputStream) inputStream2, file.length()); 

가, 일부는 finally 블록 스트림을 닫습니다 잊지 마세요 :

시도는 두 개의 입력 스트림을 제공합니다.

행운을 비네.

+0

두 개의 서로 다른 입력 스트림에서 같은 파일을 동시에 읽는 것이 예외가됩니까? 논리적으로 이것은 스레드 교착 상태와 비슷한 것을 일으킬 수 있다고 생각할 수 있습니다. – DeanMWake

+0

둘 다 읽기만하면 문제가 발생하지 않습니다. – hendrik

1

내 생각 엔 처음 setBinaryStream과() 스트림을 소모입니다 ... 감사 할 이유를 모르겠어요. 따라서 setBinaryStream()에 대한 두 번째 호출은 단순히 "null"을 읽습니다.

관련 문제