2

我需要做的(我知道这是不好的做法,但我有点被迫)是从 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();
4

2 回答 2

3

您应该必须使用INSERTor UPDATEsql 语句来添加新记录或更新现有行。

String sql="INSERT INTO TableName (Col1,Col2) VALUES (?,?)";

使用?(问号)指定占位符。

编辑:

Connection connection=null;
PreparedStatement statement=null;
String sql="UPDATE TableName set ImageCol1=? WHERE ID=?";
try{
  //Obtain connection 
  statement=connection.prepareStatement(sql);
  statement.setBytes(1,byteArray);
  statement.setInt(2,10);
  ...
}catch(SQLException ex){
  //
}finally{
  if(ps!=null) {
    try{
      ps.close();
    }catch(Exception ex){
      //
    }
  }
 if(cn!=null) {
    try{
      cn.close();
    }catch(Exception ex){
      //
    }
  }
}
于 2012-07-02T13:03:43.720 回答
1

你应该这样做:

Connection con = getConnection();
PreparedStatement ps = null;
con = getConnection();
ps = con.prepareStatement("insert into tableName (column, blobColumn...) values (?, ?)");
ps.setString(1, "ID");
File image = new File("C:/yourPath.../...");
inputStream = new FileInputStream(image);
ps.setBinaryStream(2, (InputStream) inputStream, (int) (image.length()));
ps.executeUpdate();

就是这样,现在您将 img 插入 DB。

于 2014-07-22T17:31:02.137 回答