2013-12-16 97 views
2

我有我的程序中的客戶類和訪問數據庫中的客戶表,我想通過給定的值更新數據庫中的客戶餘額。 我寫了所有似乎是正確的語句,但不幸的是數據庫不受影響。 這是我使用的提前更新DB 感謝法數據庫沒有更新ADO.Net

public static bool UpdateCustomer(Customer customer) 
{ 
    bool EditSucceeded = false; 
    string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\GarageProTuning.accdb;"; 

    using (OleDbConnection _con = new OleDbConnection(connectionString)) 
    { 
     string commandText = "UPDATE Customer SET [email protected] WHERE [email protected]"; 

     using (OleDbCommand _cmd = new OleDbCommand(commandText, _con)) 
     { 
     _cmd.Parameters.AddWithValue("@CustomerID", customer.CustomerID); 
     _cmd.Parameters.AddWithValue("@Balance", customer.Balance); 
     _con.Open(); 
     int rowsAffected = _cmd.ExecuteNonQuery(); 
     if (rowsAffected > 0) 
      EditSucceeded = true; 
     _con.Close(); 
     } 
    } 
    return EditSucceeded; 
} 
+0

爲什麼關閉連接兩次? – Brian

+0

只是複製錯誤。 :) –

+0

我想添加一個通知,當我用靜態值(不帶參數)重寫了commandtext時,它會成功更新數據庫 –

回答

3

您有:

public static bool UpdateCustomer(Customer customer) 
{ 
    bool EditSucceeded = false; 
    string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\GarageProTuning.accdb;"; 

    using (OleDbConnection _con = new OleDbConnection(connectionString)) 
    { 
     string commandText = "UPDATE Customer SET [email protected] WHERE [email protected]"; 

     using (OleDbCommand _cmd = new OleDbCommand(commandText, _con)) 
     { 
     _cmd.Parameters.AddWithValue("@CustomerID", customer.CustomerID); 
     _cmd.Parameters.AddWithValue("@Balance", customer.Balance); 
     _con.Open(); 
     int rowsAffected = _cmd.ExecuteNonQuery(); 
     if (rowsAffected > 0) 
      EditSucceeded = true; 
     _con.Close(); 
     } 
    } 
    return EditSucceeded; 
} 

你需要的是:

public static bool UpdateCustomer(Customer customer) 
{ 
    bool EditSucceeded = false; 
    string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\GarageProTuning.accdb;"; 

    using (OleDbConnection _con = new OleDbConnection(connectionString)) 
    { 
     string commandText = "UPDATE Customer SET [email protected] WHERE [email protected]"; 

     using (OleDbCommand _cmd = new OleDbCommand(commandText, _con)) 
     { 
     _cmd.Parameters.AddWithValue("@Balance", customer.Balance); // Explanation below 
     _cmd.Parameters.AddWithValue("@CustomerID", customer.CustomerID); 
     _con.Open(); 
     int rowsAffected = _cmd.ExecuteNonQuery(); 
     if (rowsAffected > 0) 
      EditSucceeded = true; 
     _con.Close(); 
     } 
    } 
    return EditSucceeded; 
} 

OleDbCommand.Parameters非常特別是動物當談到他們如何被添加/處理。從文檔我地連接:

因此,在這種OleDbParameter對象添加到OleDbParameterCollection的順序必須直接對應於問號佔位符在命令文本的參數的位置。

簡而言之,你必須相同順序,它們出現在你的命令文本添加參數。