再次遭遇奇怪的问题。

表结构
----------------------------------
Id  自增字段
Subject
Content

当我要使用以下代码更新Id=13的记录时,永远不会成功,也没有任何异常抛出。直接使用sql语句测试时更新成功。

  static void TestOleDb()
  {
   using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\database.mdb;Persist Security Info=False"))
   {
    conn.Open();

    string sql = "update [news] set subject=@subject, content=@content where id=@id";
    OleDbCommand cmd = new OleDbCommand(sql, conn);
    cmd.Parameters.Add(new OleDbParameter("@id", 13));
    cmd.Parameters.Add(new OleDbParameter("@subject", "subject"));
    cmd.Parameters.Add(new OleDbParameter("@content", DateTime.Now.ToString()));
    Console.WriteLine(cmd.ExecuteNonQuery());

   }
  }

我开始怀疑OleDb存在问题,我们继续看下面的代码。

  static void TestOleDb()
  {
   using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\database.mdb;Persist Security Info=False"))
   {
    conn.Open();

    string sql = "insert into [news] ([Content], [Subject]) values (@Content, @Subject)";
    OleDbCommand cmd = new OleDbCommand(sql, conn);
    cmd.Parameters.Add(new OleDbParameter("@subject", "subject"));
    cmd.Parameters.Add(new OleDbParameter("@content", DateTime.Now.ToString()));
    Console.WriteLine(cmd.ExecuteNonQuery());
   }
  }

测试结果出现了如下一条记录

Id     Subject                Content
---------------------------------------------------------
14    2005-2-20 13:0:1   Subject

由此我断定应该是OleDb的问题,它并不是按Parameter Name来构造Sql语句,而是按 Parameters.Index。于是将最初
的代码进行修改,完全按照Sql语句中参数出现的先后添加参数对象,结果记录被正确更新。

  static void TestOleDb()
  {
   using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\database.mdb;Persist Security Info=False"))
   {
    conn.Open();

    string sql = "update [news] set subject=@subject, content=@content where id=@id";
    OleDbCommand cmd = new OleDbCommand(sql, conn);
    cmd.Parameters.Add(new OleDbParameter("@subject", "subject"));
    cmd.Parameters.Add(new OleDbParameter("@content", DateTime.Now.ToString()));
    cmd.Parameters.Add(new OleDbParameter("@id", 13));
    Console.WriteLine(cmd.ExecuteNonQuery());

   }
  }


郁闷!该问题在SqlClient中不存在。