2014-07-20 70 views
1

我想在C#来更新我的Access数据库,我真的不为什么不working.My代码:更新数据库访问,C#

public void EditAlbum (Album newAlbum) 
    { 
     command.CommandText = "UPDATE Album SET [Name][email protected], [Description][email protected], [Location][email protected], [Date][email protected],[CoverPhotoURL][email protected] WHERE [ID][email protected]"; 

     command.Parameters.AddWithValue("@Name", newAlbum.Name); 
     command.Parameters.AddWithValue("@Description", newAlbum.Description); 
     command.Parameters.AddWithValue("@Location", newAlbum.Location); 
     command.Parameters.AddWithValue("@Data", newAlbum.Date); 
     command.Parameters.AddWithValue("@Id", newAlbum.ID); 
     command.Parameters.AddWithValue("@Cover", newAlbum.CoverPhoto); 
     command.ExecuteNonQuery(); 
    } 

我的数据库有一个字段,顺序如下:ID,名称,描述,地点,日期,CoverPhotoURL。 我没有收到任何错误消息,但是这段代码什么都不做。

+1

的确切顺序的参数你设置一个断点并验证到达的代码? – mason

+1

你怎么知道它什么都不做?你没有在数据库中得到预期的结果?查询是否实际在数据库上执行(您可以使用Profiler查看它)吗? – dotnetom

+0

您是否曾尝试在该代码块周围放置try/catch块以使100%确定该数据库不返回错误? –

回答

3

问题是您将参数添加到集合的顺序。
OleDb不能通过它们的名字来识别参数,而只能通过它们的位置来识别。
所以你需要添加在其各自的占位符出现在查询

public void EditAlbum (Album newAlbum) 
{ 
    command.CommandText = @"UPDATE Album SET [Name][email protected], 
          [Description][email protected], 
          [Location][email protected], 
          [Date][email protected], 
          [CoverPhotoURL][email protected] 
          WHERE [ID][email protected]"; 

    command.Parameters.AddWithValue("@Name", newAlbum.Name); 
    command.Parameters.AddWithValue("@Description", newAlbum.Description); 
    command.Parameters.AddWithValue("@Location", newAlbum.Location); 
    command.Parameters.AddWithValue("@Data", newAlbum.Date); 
    command.Parameters.AddWithValue("@Cover", newAlbum.CoverPhoto); 
    // Moved after the Cover parameter 
    command.Parameters.AddWithValue("@Id", newAlbum.ID); 
    command.ExecuteNonQuery(); 
} 
+1

哇,我不知道它需要按顺序。我以为参数使用了一种'String.Replace'形式,谢谢你,你可能已经把我从未来的bug中拯救了出来。 :) –

+1

这是OleDb的一个特点,如果您使用SqlClient或MySql提供程序,您可以毫无问题地按顺序添加参数。但参数值永远不会使用字符串连接的形式来替换。这将打败他们最大的好处(无Sql注入和没有解析问题)他们被传递到数据库引擎进行正确处理 – Steve

+1

另外,OleDb使用? (问号)的参数占位符。但是Access也接受@name形式,可能与它的大表弟Sql Server兼容 – Steve