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 を使用してみましたが、Google の調査によると、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

新しいレコードを追加するか、既存の行を更新するには、INSERTまたはSQLステートメントを使用する必要があります。UPDATE

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 に答える