我的Access数据库不会更新。代码中没有错误

时间:2016-04-28 15:53:16

标签: c# oledbcommand access

我正在使用此代码更新数据库:

var connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
string commandString = string.Empty;
using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    OleDbCommand command = new OleDbCommand(commandString, con);
    commandString = "UPDATE accesscontrol SET enabled=@isEnabled WHERE proxyFor=@userNameInGrid AND currentlyLoggedOnUser=@userName";

    command.Parameters.AddWithValue("userName", Environment.UserName);
    command.Parameters.AddWithValue("isEnabled", tempPerson.isBool.ToString());
    command.Parameters.AddWithValue("userNameInGrid", tempPerson.Name);
    command.ExecuteNonQuery();
    command.Parameters.Clear();
}

1 个答案:

答案 0 :(得分:1)

因为您使用空commandString

首先你设置:

string commandString = string.Empty;

然后您将空commandString传递给OleDbCommand,之后您将值设置为变量commandString但不是OleDbCommand

OleDbCommand command = new OleDbCommand(commandString, con);
commandString = "UPDATE accesscontrol SET enabled=@isEnabled WHERE proxyFor=@userNameInGrid AND currentlyLoggedOnUser=@userName";

将您的代码更改为:

commandString = "UPDATE accesscontrol SET enabled=@isEnabled WHERE proxyFor=@userNameInGrid AND currentlyLoggedOnUser=@userName";
OleDbCommand command = new OleDbCommand(commandString, con);

<强>更新

此外,您应在参数名称

之前添加@
command.Parameters.AddWithValue("@userName", Environment.UserName);
command.Parameters.AddWithValue("@isEnabled", tempPerson.isBool.ToString());
command.Parameters.AddWithValue("@userNameInGrid", tempPerson.Name);
相关问题