2012-05-02 12 views
1

私はそれが私が間違ってここにいるのか分かりません - ファイル名の変更は私の更新コマンドのために引き出しているデータセットに対して正しく行われますが、私はデータベースをチェックするとその後変更が行われていない...ので、私は少し混乱しています...MS Accessのテーブルを更新するためのOleDbDataAdapter、なぜ私の更新プログラムは動作しませんか?

using (System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + 
           "Data Source=J:\\Physics.mdb")) 
     { 
      using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter("select thesisID, filename FROM Theses", con)) 
      { 

       DataSet ds = new DataSet(); 
       con.Open(); 
       dbAdapter.Fill(ds); 

       for (int j = 0; j < ds.Tables[0].Rows.Count; j++) 
       { 
        ds.Tables[0].Rows[j]["filename"] = ds.Tables[0].Rows[j]["filename"].ToString().Replace(',', '_'); 
        string newFileName = ds.Tables[0].Rows[j]["filename"].ToString(); 
        int ID = Convert.ToInt32(ds.Tables[0].Rows[j]["thesisID"].ToString()); 
        using (OleDbCommand updateCommand = con.CreateCommand()) 
        { 
         updateCommand.CommandText = "update theses set filename = @newFileName where thesisID = @ID"; 
         updateCommand.Parameters.AddWithValue("@ID", ID); 
         updateCommand.Parameters.AddWithValue("@newFileName", newFileName); 

         updateCommand.ExecuteNonQuery(); 


        } 



       } 
       con.Close(); 
       } 

     } 
+1

パラメータの追加順序を逆にしてください!それは私が恐れているOleDBommandの性質です - http://stackoverflow.com/questions/1476770/oledbcommand-parameters-order-and-priorityを参照してください。 SqlClientのような他のデータプロバイダは、名前付きのパラメータをサポートしており、コードは問題ありません。 – dash

+0

アドバイスをありがとう@MichaelTodd。私は閉じた質問がまだ「アクセス可能」であることに気づいていなかった – dash

答えて

4

あなたはパラメータを追加する順序を逆にしてみてください。このため

using (OleDbCommand updateCommand = con.CreateCommand()) 
{ 
    updateCommand.CommandType = CommandType.Text; 
    updateCommand.CommandText = "update theses set filename = @newFileName where thesisID = @ID"; 
    updateCommand.Parameters.AddWithValue("@newFileName", newFileName); 
    updateCommand.Parameters.AddWithValue("@ID", ID); 
    updateCommand.ExecuteNonQuery(); 
} 

理由がありますそのOleDb doesn't support named parameters、あなたがそれらを追加する順序が重要です。 OLEDBクエリがこのように表現見るために、多くの場合、一般的であることを

注:

using (OleDbCommand updateCommand = con.CreateCommand()) 
{ 
    updateCommand.CommandType = CommandType.Text; 
    updateCommand.CommandText = "update theses set filename = ? where thesisID = ?"; 
    updateCommand.Parameters.Add(new OleDbParameter("", "", ""...)); 
    updateCommand.Parameters.Add(new OleDbParameter("", "", ""...)); 
    updateCommand.ExecuteNonQuery(); 
} 

これは順序が重要であることを強調 - 疑問符は、単にパラメータが追加された順に置き換えますプレースホルダですコマンドに。

関連する問題