2016-08-19 177 views
-1
//Convert binary image file to byte array to base64 encoded string 
      FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png"); 
      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
      byte[] b = new byte[1024]; 
      int bytesRead = 0; 
      while ((bytesRead = mFileInputStream.read(b)) != -1) { 
       bos.write(b, 0, bytesRead); 
      } 
      byte[] ba = bos.toByteArray(); 
      byte[] encoded = Base64.getEncoder().encode(ba); 
      connection = DriverManager.getConnection(connectionString); 
      String insertSql = "INSERT INTO test (image) VALUES " 
        + "("+encoded+")"; 
      System.out.println(insertSql); 
      prepsInsertProduct = connection.prepareStatement( 
       insertSql); 
      System.out.println(prepsInsertProduct.execute()); 

試圖將圖像插入到sql server中,並且需要將圖像作爲base64格式。我正在接受例外。請讓我知道什麼類型的數據類型以及如何在sql server中以base64的形式插入圖像。嘗試將Base64圖像插入到sql server數據庫中

輸出:

 INSERT INTO test (image) VALUES ([[email protected]) 
     java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ']' not found. 
    at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:1270) 
    at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:165) 
    at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.<init>(JtdsPreparedStatement.java:111) 
    at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2492) 
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2450) 
at base64upload.base64upload.App.main(App.java:70) 
+0

']'沒有找到,所以在價值觀像結尾處添加']'到您的查詢([B @ 7229724f']') –

+1

@ZaidYasyaf謝謝,你用這個建議讓我的日子過得很開心 – Andremoniy

+0

爲什麼你想要Base64首先對字節進行編碼?你會浪費不必要的空間。 – Kayaman

回答

1

你只是串聯串的字節數組toString()值。這是不正確的。你應該用另一種方法:

String insertSql = "INSERT INTO test (image) VALUES (?)"; 
    System.out.println(insertSql); 
    prepsInsertProduct = connection.prepareStatement(insertSql); 
    // here set your array 
    prepsInsertProduct.setBytes(encoded); 
相關問題