2016-07-11 16 views
0

私は.Thisは私がこれまで持っているものである私は、テーブルを更新するために、すべての私のアプリケーション全体で使用することができますמ更新クエリ(インベントリ)を思い付くしようとしています:JavaのアップデートのPreparedStatement

public void updateInventory(Inventory inventory){ 
    PreparedStatement ps=null; 
    try { 
     String query = 
      "UPDATE "+TableName.INVENTORY +" "+ 
      "SET quantity=IFNULL(?, quantity), full_stock=IFNULL(?, full_stock), reorder_level=IFNULL(?, reorder_level), selling_price=IFNULL(?, selling_price), delete_status=IFNULL(?, delete_status), product_id=IFNULL(?, product_id) "+ 
      "WHERE id = ? OR product_id=IFNULL(?, product_id) "; 
     connection = hikariDS.getConnection(); 
     ps = connection.prepareStatement(query); 
     ps.setFloat(1,inventory.getQuantity()); 
     ps.setFloat(2,inventory.getFullStock()); 
     ps.setFloat(3,inventory.getReorderLevel()); 
     ps.setFloat(4,inventory.getPrice()); 
     ps.setInt(5, inventory.getDeleteStatus()); 
     ps.setInt(6, inventory.getProdId()); 
     ps.setInt(7, inventory.getId()); 
     ps.setInt(8, inventory.getProdId()); 
     ps.executeUpdate(); 
    } catch(SQLException e){ e.printStackTrace();} 
    finally{ 
     if(connection != null){ 
      try {connection.close();} 
      catch (SQLException ex) {logger.log(Level.SEVERE, null, ex);} 
     } 
     if(ps != null){ 
      try { ps.close();} 
      catch (SQLException ex) { logger.log(Level.SEVERE, null, ex);} 
     } 
    } 
} 

上記のクエリオブジェクト内の新しい値で列を更新することが想定されていますが、設定されていない場合は、列の既存の値を入力するだけです。

問題がある:インベントリオブジェクトから取得した値がヌルであるか、または0の値ならば、それは既存の値で更新されません。

+1

どのようにインベントリオブジェクトは '0'することができます:null以外ゲッターについては

ps.setBigDecimal(1, inventory.getQuantity()); 

は、IF()を使いますか? –

+0

このリンクを試してみてください。.. http://stackoverflow.com/questions/32018418/update-columns-if-input-values-are-not-null-otherwise-ignore-and-keep-the-existi –

+0

ないオブジェクト自体しかし、属性。例えば私は、価格だけを更新したいが、数量が設定されていないので、私は、価格属性に値が含まれますが、量はゼロ –

答えて

1

私は(inventoryの)あなたのjava側の値がnullの場合も想定し、そしてあなたは、値のすべての組み合わせのためのコードの一枚を持っていると思います。

IFNULL(NULLを、...)を取得するのにSQLは次のように、あなたのゲッターはオブジェクトラッパーを返すことを想定し、罰金だ:あなたは

ps.setObject(1, inventory.getQuantity()); 
を呼び出す必要が

Float getQuantity() 

ところで、Java側ではBigDecimal、SQLスキーマ側ではDECIMALが良い選択です。浮動小数点の丸め誤差。これが有効になります。

SET quantity = IF(? = 0.0, quantity, ?), 

ps.setDouble(1, inventory.getQuantity()); 
ps.setDouble(2, inventory.getQuantity()); 
1

あなたが実際に指定されたパラメータに値を設定し、何もありません。

SET quantity=IFNULL(?, quantity), full_stock=IFNULL(?, full_stock), reorder_level=IFNULL(?, reorder_level), selling_price=IFNULL(?, selling_price), delete_status=IFNULL(?, delete_status), product_id=IFNULL(?, product_id) "+ 
     "WHERE id = ? OR product_id=IFNULL(?, product_id) 

これは、あなたが、もちろん、すべてのパラメータを複製する必要があります意味など

SET quantity=IFNULL(?, quantity, ?), ... 

でなければなりません。

+0

私は追加しましたか?あなたが提案したIFNULL関数の3番目のパラメータとして、java.sql.SQLException:パラメータ9に値が指定されていません。 。 .. –

関連する問題