//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());
Trying to insert image to sql server and need to have the image as base64 format. I am getting below exception. Please let me know what type of datatype and how to insert image as base64 in sql server.
尝试将图像插入sql server并需要将图像作为base64格式。我正在低于例外。请让我知道什么类型的数据类型以及如何在sql server中将图像作为base64插入。
Output :
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 个解决方案
#1
1
You are just concatenating string with toString()
value of byte array. That's incorrect. You should use another approach:
您只是将字符串与字节数组的toString()值连接起来。那是不对的。你应该使用另一种方法:
String insertSql = "INSERT INTO test (image) VALUES (?)";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
// here set your array
prepsInsertProduct.setBytes(encoded);
#1
1
You are just concatenating string with toString()
value of byte array. That's incorrect. You should use another approach:
您只是将字符串与字节数组的toString()值连接起来。那是不对的。你应该使用另一种方法:
String insertSql = "INSERT INTO test (image) VALUES (?)";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
// here set your array
prepsInsertProduct.setBytes(encoded);