2016-08-19 277 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); 
相关问题