尝试将Base64映像插入sql server数据库

时间:2016-08-19 07:56:08

标签: java sql-server sql-server-2008

 //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插入。

输出:

        INSERT INTO test (image) VALUES ([B@7229724f)
        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) 

1 个答案:

答案 0 :(得分:1)

您只是将字符串与字节数组的toString()值连接起来。那是不对的。你应该使用另一种方法:

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