2017-10-11 12 views
-1

jdbcを使用して更新クエリを作成しています。しかし、条件に基づいて私は列に異なる値を設定する必要があります。このコードをより簡単なコードとして変更できますか?あなたのアイデアを教えてください。Javaを使用した一般的なjdbc更新クエリ

if(allDealsCreated) { 
    System.out.println("Updating the status of the deals as CLOSED"); 
    if(deals != null && !deals.isEmpty()) {    
     for (String dealId : deals) { 
      PreparedStatement closedPreparedStatement = null; 
      try (Connection con = DriverManager.getConnection(
       "jdbc:as400://localhost/BB", 
       "<username>", 
       "<password>")) { 

      String sql = "<Update query to set status as closed>"; 
      closedPreparedStatement = con.prepareStatement(sql); 
      closedPreparedStatement.executeUpdate(); 

     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
} else { 
System.out.println("Updating the status of the deals as NEW"); 
if(deals != null && !deals.isEmpty()) {    
    for (String dealId : deals) { 
     PreparedStatement newPreparedStatement = null; 
     try (Connection con = DriverManager.getConnection(
       "jdbc:as400://localhost/BB", 
       "<username>", 
       "<password>")) { 

      String sql = "<Update query to set status as new>"; 
      newPreparedStatement = con.prepareStatement(sql); 
      newPreparedStatement.executeUpdate(); 

     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
} 
+1

あなたのコードの2つの半分の間の唯一の違いは、SQLクエリ自体であれば、おそらくそれ(とそれだけで)はallDealsCreated' 'に応じて先頭に設定する必要があります。私はまた、あなたのループの各反復ではなく、一度だけ接続を取得したいと思います。それは物事を単純化するはずです。 – dave

+0

@dave、例を挙げて説明してください。 – Yakhoob

+0

私はあなたに手渡しではなく自分で試してみることが良い学習経験と思っていたので、コードを教えてくれませんでした。しかし、それは他の誰かがちょうどそれを行ったように見えます:) – dave

答えて

2

あなたのコードに問題があります。あなたはforループでConnectionとPreparedStatementsを作成していますか?それはベストプラクティスではありません。以下のコードに従ってください。

if (deals != null && !deals.isEmpty()) { 
     try { 
      Connection con = DriverManager.getConnection(
        "jdbc:as400://localhost/BB", 
        "<username>", 
        "<password>"); 
      PreparedStatement preparedStatement = null; 
      String sql; 
      if (allDealsCreated) { 
       System.out.println("Updating the status of the deals as CLOSED"); 
       sql = "UPDATE DEALS SET STATUS = 'CLOSED' WHERE DEALNO= ?"; 
      } else { 
       System.out.println("Updating the status of the deals as NEW"); 
       sql = "UPDATE DEALS SET STATUS = 'NEW' WHERE DEALNO= ?"; 
      }      
      preparedStatement = con.prepareStatement(sql); 
      for (String dealId : deals) { 
       preparedStatement.setString(1, dealId); 
       preparedStatement.addBatch(); 
      } 
      preparedStatement.executeBatch(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
+0

私はこの点を得ていませんparamIndex = 0; 、パラメータはすでに正しく処理されています – Yakhoob

+0

「取引」チェックを外に動かすので、答えようとしていたよりもうまくいっています。 –

+0

クエリを渡すパラメータがありますか? –

関連する問題