2012-09-01 60 views
2

任何人都可以告訴下面的代碼中出現了什麼問題嗎?OleDb使用參數值更新sql不更新Access中的記錄

command.Connection = ConnectionManager.GetConnection(); 
command.CommandText = "Update Table1 SET Replaceme = ? WHERE Searchme = ?"; 
command.CommandType = CommandType.Text; 
command.Parameters.AddWithValue("Replaceme", "Goodman"); 
command.Parameters.AddWithValue("Searchme", "Anand"); 

command.Connection.Open(); 
int recordsaffected = command.ExecuteNonQuery(); 
MessageBox.Show("Records affected : " + recordsaffected); 

MessageBox顯示0條記錄,它實際上沒有更新可用的記錄。

表名(Table1)和列名(Replaceme and Searchme)正確拼寫。

+1

洛爾在所有的SQL Server開發人員發佈誰不使用System.Data.OleDb –

+0

答案是否有在Searchme柱「阿南德一排」?你在看數據庫嗎?即它是連接字符串中指定的一個。你有沒有交易,你沒有提交? –

+1

@ ta.speot.is:嗨,先生知道這一切。給你的解決方案。 –

回答

-1

它不工作,因爲您正在使用?而不是參數化查詢。

使用此,它應該工作:

Update Table1 SET Replaceme = @Replaceme WHERE Searchme = @Searchme

+0

請參見備註:http://msdn.microsoft.com/zh-cn/library/system.data.oledb.oledbparameter –

6

首先,OleDbParameter s爲位置,沒有命名。閱讀備註中的documentation部分。不理會任何不理解這一點的答案。

這是一個最小的工作示例。

首先,創建數據庫:

enter image description here

enter image description here

其次,編寫代碼:

using System; 
using System.Windows.Forms; 
using System.Data.OleDb; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string connectionString; 
      connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"; 
      connectionString += "Data Source=C:\\Temp\\Database1.mdb"; 

      using (var connection = new OleDbConnection(connectionString)) 
      { 
       connection.Open(); 

       var command = connection.CreateCommand(); 
       command.CommandText = 
        "UPDATE Table1 SET Replaceme = ? WHERE Searchme = ?"; 

       var p1 = command.CreateParameter(); 
       p1.Value = "Goodman"; 
       command.Parameters.Add(p1); 

       var p2 = command.CreateParameter(); 
       p2.Value = "Anand"; 
       command.Parameters.Add(p2); 

       var result = String.Format("Records affected: {0}", 
        command.ExecuteNonQuery()); 
       MessageBox.Show(result); 
      } 
     } 
    } 
} 

結果:

enter image description here

enter image description here

+0

感謝您的努力。你給的解決方案也適用於我 – Anand

+0

@Anand沒有問題。這種努力沒有任何意義,我對所有錯誤信息被張貼爲「答案」感到不滿。很高興它的工作! –

+0

我從這個答案中得到了什麼,這也有助於解決我與Ole Db的問題,就是你不能使用'cmd.Parameters.AddWithValue('p1','p1value');'這意味着命名變量。所以我得出結論,應該在查詢中使用'?'查找值,然後設置值以使它們出現在查詢中。 – JasonStack