locked
how to check if row has been affected? RRS feed

  • Question

  • User-2060576634 posted

    hello everyone.. how should we check if a row has been affected after the following INSERT statement so that we can create an if statement and display a success or failure message?

                   //add row to table
                              var sql = "INSERT INTO Table (Q1,Q2,Q3, StudentId) VALUES (@0,@1,@2,@3)";
                               db.Execute(sql, Request["Q1"],Request["Q2"],Request["Q3"],WebSecurity.CurrentUserId);
                                 }
                                 // Check if the row has been affected.
                        if (?  ?   ?   ?)
                        {
    Wednesday, January 14, 2015 9:19 PM

Answers

  • User-821857111 posted

    In your example, you can get the return value of the Database.Execute method which will provide the number of affected rows:

    var rowsAffected = db.Execute(sql, ...);

    The result should always be 1 for an insert statement, so retrieving that value seems pretty pointless to me. It would be more useful if you were conducting an UPDATE or DELETE statement.

    The try-catch block should be used to provide you with control over any possible exception that could be raised during the database operation. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 15, 2015 3:46 AM

All replies

  • User379720387 posted

    try catch block?

    try

    {

    your sql select here

    }

    catch (Exception ex)

    {

    figure out what exception is thrown for the various problems you may encounter with those few lines of code above.

    act accordingly

    }

    Wednesday, January 14, 2015 10:42 PM
  • User-2060576634 posted
    The soccer website tutorial uses this method.. But i cant understand how it works. And i encounter an error when i use it

    // Check if the change succeeded.
    if (rowsAffected == 1)
    {
    statusMessages.Add("You have...
    Thursday, January 15, 2015 3:10 AM
  • User-821857111 posted

    In your example, you can get the return value of the Database.Execute method which will provide the number of affected rows:

    var rowsAffected = db.Execute(sql, ...);

    The result should always be 1 for an insert statement, so retrieving that value seems pretty pointless to me. It would be more useful if you were conducting an UPDATE or DELETE statement.

    The try-catch block should be used to provide you with control over any possible exception that could be raised during the database operation. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 15, 2015 3:46 AM
  • User-2060576634 posted

    Thanks.. so I decided to just move on , showing the success message without first checking what happened!

    Thursday, January 15, 2015 7:58 AM