2014-12-25 85 views
0

我想知道爲什麼這段代碼不起作用;它總是返回零(任何受影響的行)。該數據庫是一個Access數據庫。我可以插入和刪除但不更新數據。它是一個Windows窗體C#應用程序。SQL更新命令總是返回0

 string sql = ""; 
     try 
     { 
      string[] parametrosNomes = new string[3]; 
      parametrosNomes[0] = "@CatId"; 
      parametrosNomes[1] = "@CatNome"; 
      parametrosNomes[2] = "@CatDescricao"; 

      object[] parametrosValores = new object[3]; 
      parametrosValores[0] = oCateg.categoriaid; 
      parametrosValores[1] = oCateg.categoriaNome; 
      parametrosValores[2] = oCateg.categoriaDescricao; 

      sql = "UPDATE Categorias SET categoriaNome = @CatNome, [email protected] Where [email protected]"; 
      int retorno = AcessoDB.CRUD(sql, parametrosNomes, parametrosValores); 
      return retorno; 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 

注:CRUD方法,我只填充參數和執行

int retorno = command.ExecuteNonQuery(); 
return retorno; 

我覈實了所有參數,字段的名稱和該命令沒有錯誤執行,但總是返回零並執行的SqlCommand不更新數據庫中的表。

我不能看到什麼錯在我的代碼,但它doesn't工作。

任何人都可以打開我的眼睛?

+0

不確定訪問數據庫..連接字符串或什麼?它實際上是否有任何記錄,其中categorialId = @ CatId? – CularBytes

+3

你有沒有試過你的查詢在你的數據庫管理器,如SSMS?它在那裏更新?你調試了你的代碼嗎?當你添加參數值時,你的查詢是什麼樣的?什麼是「AcessoDB」和「CRUD」?你在使用OleDb .Net Provider嗎?如果您使用OLE DB,它不支持命名參數。您需要按照您將其添加到命令中的順序提供它們。 –

+1

發佈'AcessoDB.CRUD'的代碼,人們可能會幫助你。我們缺乏通過TCP/IP閱讀您的想法來調試代碼的能力。 – nvoigt

回答

1

試試這個。參數應該與sql中的順序相同。在sql本身中,你需要使用'?'

string sql = ""; 
    try 
    { 
     string[] parametrosNomes = new string[3]; 
     parametrosNomes[0] = "@CatNome"; 
     parametrosNomes[1] = "@CatDescricao"; 
     parametrosNomes[2] = "@CatCatId"; 

     object[] parametrosValores = new object[3]; 
     parametrosValores[0] = oCateg.categoriaNome; 
     parametrosValores[1] = oCateg.categoriaDescricao; 
     parametrosValores[2] = oCateg.categoriaid; 

     sql = "UPDATE Categorias SET categoriaNome = ?, categoriaDescricao = ? Where categoriaId = ?"; 
     int retorno = AcessoDB.CRUD(sql, parametrosNomes, parametrosValores); 
     return retorno; 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
1

我想感謝大家的答案。

問題解決了:該參數不被使用它們的順序傳遞。

我只是修改參數命令:

string[] parametrosNomes = new string[3]; 
parametrosNomes[0] = "@CatNome"; 
parametrosNomes[1] = "@CatDescricao"; 
parametrosNomes[2] = "@CatId"; 
object[] parametrosValores = new object[3]; 
parametrosValores[0] = oCateg.categoriaNome; 
parametrosValores[1] = oCateg.categoriaDescricao; 
parametrosValores[2] = oCateg.categoriaid; 
sql = "UPDATE Categorias SET categoriaNome = @CatNome, [email protected] Where [email protected]"; 

現在表被正確地更新。