简体   繁体   中英

Access update statement not working in C#

I'm going crazy trying to find out the reason why the below code won't update my database. I appreciate any help.
The connection string is correct and I'm able to execute similar commands, only this one is not working for some reason. Basically what I want is to replace occurrences of the value "1" with "123" in a column that I pass to the method.

        public void removeExpired2(string column, string user)
    {
        string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\DB.accdb";

        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            OleDbCommand cmd = new OleDbCommand("UPDATE [Reservations] SET [" + column + "] = @Column WHERE [" + column + "] = @ID");
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@Column", "123");
            cmd.Parameters.AddWithValue("@ID", "1");
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(Button1, this.GetType(), "AlertMsg", "<script language='javascript'>alert('" + ex.Message.ToString() + "');</script>", false);
            }
        }
    }

Basically what I want is to replace occurrences of the value "1" with "123"

Your query is doing just opposite.

Change this

"UPDATE [Reservations] SET [" + column + "] = @Column WHERE [" + column + "] = @ID"

to

"UPDATE [Reservations] SET [" + column + "] = @ID WHERE [" + column + "] = @Column"

OR

Do this:

cmd.Parameters.AddWithValue("@Column", "123");
cmd.Parameters.AddWithValue("@ID", "1");

I had the command executed with two other commands, so I tried to separate them and it seems to have fixed the issue.
I moved one command into its own method and the remaining two are as they were before, and it's working now. Thanks everyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM