我需要做的(我知道这是不好的做法,但我有点被迫)是从 Java 将图像上传到 SQL DB。目前,我正在使用准备好的语句并尝试使用它来上传图像中的字节。
public void insertImage(Connection conn,String img,String strItemNum)
{
String query;
PreparedStatement pstmt;
try
{
File file = new File(img);
FileInputStream fis = new FileInputStream(file);
byte[] image = new byte[(int) file.length()];
fis.read(image);
System.out.println("image as sent " + image.length);
query = ("SELECT [Item Picture] from [Inventory] where [Item Number] = '" + strItemNum + "'");
pstmt = conn.prepareStatement(query);
System.out.println(pstmt.getMetaData().getColumnName(1) + " of type: " + pstmt.getMetaData().getColumnTypeName(1));
pstmt.setBytes(1,image);
pstmt.executeUpdate();
pstmt.close();
}
catch (IOException | SQLException e)
{
System.err.println(";"+e.getMessage());
e.printStackTrace();
}
}
但这会产生一个 SQLException: Invalid parameter index 1。我表中的参数是“图像”类型,我无法坚持。我试过使用 .setBlob 但从我的谷歌研究来看,Blob 似乎从来没有很好地实现过。
编辑:通过使用 AVD 的答案解决
变成
query = ("Update [Inventory] set [Item Picture] = ? where [Item Number] = ?");
pstmt = conn.prepareStatement(query);
pstmt.setBytes(1,image);
pstmt.setString(2, strItemNum);
pstmt.executeUpdate();
pstmt.close();