Java 正在尝试将Base64映像插入sql server数据库
正在尝试将映像插入sql server,并且需要将映像设置为base64格式。我越来越不正常了。请让我知道什么类型的数据类型以及如何在sql server中插入图像作为base64 输出:Java 正在尝试将Base64映像插入sql server数据库,java,sql-server,sql-server-2008,Java,Sql Server,Sql Server 2008,正在尝试将映像插入sql server,并且需要将映像设置为base64格式。我越来越不正常了。请让我知道什么类型的数据类型以及如何在sql server中插入图像作为base64 输出: //Convert binary image file to byte array to base64 encoded string FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace
//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());
插入到测试(图像)值中([B@7229724f)
java.sql.SQLException:无效的sql语句或JDBC转义,未找到终止']'。
位于net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:1270)
位于net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:165)
位于net.sourceforge.jtds.jdbc.jtdsprearedstatement.(jtdsprearedstatement.java:111)
在net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2492)
位于net.sourceforge.jtds.jdbc.JtdsConnection.preparest陈述(JtdsConnection.java:2450)
位于base64upload.base64upload.App.main(App.java:70)
您只是将字符串与字节数组的toString()值连接起来。那是不对的。您应该使用另一种方法:
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)
]
未找到,因此在查询的值末尾添加]
,如([B@7229724f]
)@ZaidySyaf谢谢,你的建议让我开心了一天。为什么要先对字节进行Base64编码?你将不必要地浪费空间。我发现base64也适用于iphone和ipad。
String insertSql = "INSERT INTO test (image) VALUES (?)";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
// here set your array
prepsInsertProduct.setBytes(encoded);