2011-09-19 7 views
0

로컬 하드 드라이브의 URL에서 가져온 이미지 인 Blob 열이있는 행을 삽입해야합니다. 나의 시도는 다음과 같습니다Java를 사용하여 데이터베이스에 이미지 삽입

File file = new File(imageURL); 
FileInputStream input; 
byte[] data = null; 
try { 
    input = new FileInputStream(file); 
    data = new byte[input.available()]; 
    input.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

은 그 때 나는 내 이미지 오브젝트를 구축 : 된 imagen IMA = 새로운 된 imagen (0, 데이터, 새 Date()); 나는 그것을 다른 관리자에게 보냅니다.

byte[] datos = image.getDatos(); 
    Blob blob = null; 
    try { 
     blob = conection.createBlob(); 
     blob.setBytes(1,datos); 
    } catch (SQLException e) {   
     e.printStackTrace(); 
    } 

    java.sql.Date sqlDate = new java.sql.Date(image.getFecha().getTime()); 

    String query = " INSERT INTO imagen VALUES('" + image.getId() + "','" 
      + blob + "','" + sqlDate + "') "; 

    int lastID = BBDD.add(query, conection); 

나는 문제없이 실행할 수 있지만, 나는 단지이 "[email protected]"내 MySQL의 doesn' 같은 것을 얻을 :이 같은 BLOB 객체로 바이트 []를 변환됩니다 내 다른 것을 보여주지 마라.

아무도 도와 줄 수 있습니까?. 나는 그것을보기 위해 SQLyog를 사용한다.

감사합니다.

+0

'InputStream.available()'은 입력 스트림에 포함 된 바이트 수를 알려주지 않습니다. 그리고 코드에서 입력 스트림을 읽지도 않습니다 ('read()'메서드를 호출해야합니다) –

답변

1

SQL 도구는 fileds에서 사용되는 유형에 대해서만 알고 있습니다. blob 또는 유사한 2 진 필드는 SQL 도구에 의해 이해되지 않고 변경없이 바로 전달됩니다. 이 이진 데이터를 데이터의 의미를 이해하는 다른 도구로 읽어야합니다. 좋아

+0

사실, ID, 데이터 및 날짜가있는 Image라는 Java Bean이 있습니다. 위의 방법으로 객체를 만든 다음이 객체를 내 BBDD에 삽입하여 정보를 얻습니다. 그래서 쿼리를 만들기 전에 이미지를 저장하기 위해 다른 API를 사용해야한다는 것을 의미합니까? – Sierra

+0

아니요. 쿼리의 데이터를 다른 API로 전달해야한다는 의미는 아닙니다. – Mark

2

당신이 준비된 문 사용할 수 있습니다 : 당신이 그런 이상한 출력을보고있는 이유

java.sql.PreparedStatement ps = 
         connection.prepareStatement("UPDATE table SET file = ?"); 
ps.setBinaryStream(1, new FileInputStream(file), (int)file.length()); 

UPDATE toString()가 호출됩니다

Blob의 기본을 수있는 유일한 방법은 사용하는 것 PreparedStatements, 제발 누군가를 짜내고 있다면 정정 해주세요.

public void insert() throws Exception { 
    Connection conn = null; 
    PreparedStatement ps = null; 

    InputStream is = null; 
    try { 
     conn = this.connection.getConnection(); 
     String sql = "INSERT INTO Table (image) VALUES (?)"; 

     ps = conn.prepareStatement(sql); 
     if (this.file != null && this.file.canRead()) { 
      is = new BufferedInputStream(new FileInputStream(this.file)); 
      ps.setBinaryStream(1, is, (int) this.file.length()); 
     } else { 
      ps.setNull(1, Types.BLOB); 
     } 
    } catch (Exception e) { 
     LOG.error("", e); 
     throw e; 
    } finally { 
     FileUtil.close(is); 
     DAOUtil.close(conn); 
    } 
} 

그리고 연결 개체가 있으면 이번에는 BBDD를 건너 뛸 수 있습니다.

+0

데이터베이스에 삽입하는 코드를 표시 할 수 있습니까? –

+0

내가 쿼리를 수행하는 방식 때문에 prepasesStatement를 사용할 수 없습니다. Statement?를 사용하여 수행 할 수있는 방법이 있습니까? 대단히 감사합니다 !! – Sierra

+0

진지하게, 미래의 사용자를 위해이 대답을 약간 털어 내십시오. 그렇지 않은 경우 투표가 중단되거나 신고 될 수 있습니다. – cwallenpoole

0
package com.technicalkeeda; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.InputStream; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 

public class InsertImageTest { 

    /** 
    * This is used to get the Connection 
    * 
    * @return 
    */ 
    public Connection getConnection() { 
     Connection connection = null; 

     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      connection = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/technicalkeeda", "root", ""); 
     } catch (Exception e) { 
      System.out.println("Error Occured While Getting the Connection: - " 
        + e); 
     } 
     return connection; 
    } 

    /** 
    * Insert Image 
    */ 
    public void insertImage() { 
     Connection connection = null; 
     PreparedStatement statement = null; 
     FileInputStream inputStream = null; 

     try { 
      File image = new File("C:/honda.jpg"); 
      inputStream = new FileInputStream(image); 
      connection = getConnection(); 
      statement = connection 
        .prepareStatement("insert into trn_imgs(img_title, img_data) " 
          + "values(?,?)"); 
      statement.setString(1, "Honda Car"); 
      statement.setBinaryStream(2, (InputStream) inputStream, 
        (int) (image.length())); 

      statement.executeUpdate(); 
     } catch (FileNotFoundException e) { 
      System.out.println("FileNotFoundException: - " + e); 
     } catch (SQLException e) { 
      System.out.println("SQLException: - " + e); 
     } finally { 
      try { 
       connection.close(); 
       statement.close(); 
      } catch (SQLException e) { 
       System.out.println("SQLException Finally: - " + e); 
      } 
     } 

    } 

    /*** 
    * Execute Program 
    * 
    * @param args 
    * @throws SQLException 
    */ 
    public static void main(String[] args) throws SQLException { 
     InsertImageTest imageTest = new InsertImageTest(); 
     imageTest.insertImage(); 
    } 

} 
관련 문제