2013-02-28 99 views
3

我做了一個程序,保存和更新數據庫中的數據,我可以保存和讀取數據,我也可以更新但問題是,我不能選擇"ID"作爲索引,這裏是我的使用"ID"作爲指數樣本代碼,Oledb更新命令

   cmd = new OleDbCommand(); 
       cmd.CommandType = CommandType.Text; 
       cmd.CommandText = "UPDATE Records SET FirstName = @firstname, LastName = @lastname, Age = @age, Address = @address, Course = @course WHERE [ID] = @id"; 
       cmd.Parameters.AddWithValue("@id", int.Parse(label7.Text)); 
       cmd.Parameters.AddWithValue("@firstname", textBox1.Text); 
       cmd.Parameters.AddWithValue("@lastname", textBox2.Text); 
       cmd.Parameters.AddWithValue("@age", textBox3.Text); 
       cmd.Parameters.AddWithValue("@address", textBox4.Text); 
       cmd.Parameters.AddWithValue("@course", textBox5.Text); 
       cmd.Connection = cn; 
       cn.Open(); 
       cmd.ExecuteNonQuery(); 
       { 
        MessageBox.Show("Update Success!"); 
        cn.Close(); 
       } 

這裏是我更新的代碼工作,但該指數是"firstname"

cmd = new OleDbCommand(); 
       cmd.CommandType = CommandType.Text; 
       cmd.CommandText = "UPDATE Records SET FirstName = @firstname, LastName = @lastname, Age = @age, Address = @address, Course = @course WHERE FirstName = @firstname"; 
       //cmd.Parameters.AddWithValue("@id", int.Parse(label7.Text)); 
       cmd.Parameters.AddWithValue("@firstname", textBox1.Text); 
       cmd.Parameters.AddWithValue("@lastname", textBox2.Text); 
       cmd.Parameters.AddWithValue("@age", textBox3.Text); 
       cmd.Parameters.AddWithValue("@address", textBox4.Text); 
       cmd.Parameters.AddWithValue("@course", textBox5.Text); 
       cmd.Connection = cn; 
       cn.Open(); 
       cmd.ExecuteNonQuery(); 
       { 
        MessageBox.Show("Update Success!"); 
        cn.Close();` 
       }` 

它的工作原理,但問題是我無法更新"FirstName",有沒有辦法讓我可以是否更新名字?或使用"ID"作爲索引?謝謝

回答

3

我不知道你反對什麼數據庫,但是,我不知道OleDB是否對你的參數的序數順序挑剔。即:您是否嘗試將您的「ID」參數放在最後的位置以匹配更新命令字段的實際順序?我不知道它是否會拋出。

+0

但在刪除命令,我可以成功刪除使用'「ID」',我沒有錯誤在更新,但它不是更新, – Pyromancer 2013-02-28 03:27:41

+0

是的,你是對的,它拋出了第一個參數的值,我把'cmd.Parameters.AddWithValue(「@ id」,label7.Text);'放在最後一行,它現在可以完美工作了, 謝謝 :) – Pyromancer 2013-02-28 03:33:40

2

你應該的ID最後一行後添加以下代碼:

cmd = new OleDbCommand(); 
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "UPDATE Records SET FirstName = @firstname, LastName = @lastname, Age = @age, Address = @address, Course = @course WHERE [ID] = @id"; 
cmd.Parameters.AddWithValue("@firstname", textBox1.Text); 
cmd.Parameters.AddWithValue("@lastname", textBox2.Text); 
cmd.Parameters.AddWithValue("@age", textBox3.Text); 
cmd.Parameters.AddWithValue("@address", textBox4.Text); 
cmd.Parameters.AddWithValue("@course", textBox5.Text); 
cmd.Parameters.AddWithValue("@id", int.Parse(label7.Text)); 
cmd.Connection = cn; 
cn.Open(); 
cmd.ExecuteNonQuery(); { 
    MessageBox.Show("Update Success!"); 
    cn.Close(); 
}