Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL query ExecuteNonQuery(); is not working

Folks, it might be a silly and simple question for you, but what is wrong with this simple code? The second query " in //" which is the direct value works fine but the first query execution (rowsAffected) does return a value of 0.

try
{
    using (con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("/App_Data/assets/DB.accdb") + "; Persist Security Info=False"))
    {
        con.Open();

        string query = "UPDATE tblTimeSheetDataTemp SET WBSID = @pWBSID, ProjectID = @pProjectID, FridayWorkHours = @pFridayWorkHours WHERE ID = @pid";

        //string query = "UPDATE tblTimeSheetDataTemp SET WBSID ='020501', ProjectID = '20232001', FridayWorkHours = '1' WHERE ID = 79";

        OleDbCommand sqlCmd = new OleDbCommand(query, con);

        sqlCmd.Parameters.AddWithValue("@pid", "'79'");
        sqlCmd.Parameters.AddWithValue("@pWBSID", "'020501'");
        sqlCmd.Parameters.AddWithValue("@pProjectID", "'20232001'");
        sqlCmd.Parameters.AddWithValue("@pFridayWorkHours", "1");

        int rowsAffected = sqlCmd.ExecuteNonQuery();
        con.Close();

        timesheetID.EditIndex = -1;
        populategridview();

        lblsucess.Text = query;//"Selected Record Updated";
        Lblerror.Text = "";
    } // using
}  // try
catch (Exception ex)
{
    lblsucess.Text = "";
    Lblerror.Text = ex.Message;
}  // catch

The rowsAffected which is output of ExecuteNonQuery() with the value of 0.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re using OleDbCommand to query MS Access – but OleDB does NOT support named parameters (@pid).

OleDB parameters are positional, e.g. you need to provide the parameters in the same order as they appear in your query text

@pWBSID, @pProjectID, @pFridayWorkHours, @pid

Since you’re not doing that, most likely, the UPDATE just doesn’t find a row to update – thus the rowsAffected is 0 – because nothing was in fact updated…..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading