0

I have searched for solutions but I can't find one; please help.

I have this code fragment in C#:

using (SqlCommand command = new SqlCommand())
{
    command.Connection = openCon;
    command.CommandType = CommandType.Text;
    command.CommandText = "update logRecords set totalHours = DATEDIFF(HOUR,timeIn,timeOut)";

    try
    {
        openCon.Open();
        int recordsAffected = command.ExecuteNonQuery();
        MessageBox.Show("Records affected: " + recordsAffected);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         openCon.Close();
         GetLogData();
     }
}

but it doesn't work. It didn't show the message box in the try block neither the one in the catch block.

Thanks for helping :D

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

1

You can access query with parameters, hope this help:

using(var openCon = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand())
{
    command.Connection = openCon;
    command.CommandType = CommandType.Text;
    command.CommandText = "update logRecords set totalHours = DATEDIFF(HOUR,@timeIn,@timeOut)";

    try
    {
        openCon.Open();
        command.Parameters.AddWithValue("@timeIN", timeIn);
        command.Parameters.AddWithValue("@timeOut", timeOut);
        int recordsAffected = command.ExecuteNonQuery();
        MessageBox.Show("Records affected: " + recordsAffected);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    GetLogData();
}
mason
  • 31,774
  • 10
  • 77
  • 121
Nam Doan
  • 51
  • 5
  • This is the better answer, but downvotes: 1. random indenting; 2. not using a `using` block. – Richard Sep 22 '17 at 13:36
  • AddWithValue has [performance implications](https://stackoverflow.com/questions/21263536/addwithvalue-sql-injection-safe-why). – mason Sep 22 '17 at 14:13
-1

First of all I will create Stored procedure and I will update any of my table through procedure.

So, Basic SP will be like below, and I will run it in a Database(SQL).

CREATE PROCEDURE Set_LogRecords_TotalHours
    -- Add the parameters for the stored procedure here
    @timeIn     datetime,
    @timeOut    datetime
AS
BEGIN
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    UPDATE  LogRecords 
    SET     TotalHours = DATEDIFF(HOUR, @timeIn, @timeOut)

    -- returns number of rows
    SELECT @@ROWCOUNT
END
GO

Now, I will Move to code side.

I will Create a Generic method to call All of mine Stored procedures, see below.

public static DataSet GetRecordWithExtendedTimeOut(string SPName, params SqlParameter[] SqlPrms)
    {

        DataSet ds = new DataSet();

        try
        {
            //here give reference of your connection and that is "openCon"
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand(SPName, conn))
                {
                    command.Parameters.AddRange(SqlPrms);
                    command.CommandTimeout = 0;
                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;

                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
                    {
                        try
                        {
                            dataAdapter.SelectCommand = command;
                            dataAdapter.Fill(ds);
                        }
                        catch (Exception ex)
                        {                                
                            return null;
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            //Handle Errror
        }

        return ds;          
    }

Now at last, call this method from wherever you need to access database.

Over here is the example of calling generic method.

    //Add all the parameter that you want to pass to SP, here we have 2 and they are in DAteTime Formate
SqlParameter[] parameters = 
                    {
                        new SqlParameter { ParameterName = "@timeIn", Value = ValueOf_TimeIN_DateTIME }
                        new SqlParameter { ParameterName = "@timeOut", Value = ValueOf_TimeOUT__DateTIME}
                    };

DataSet ds = DAL.GetRecordWithExtendedTimeOut("Set_LogRecords_TotalHours", parameters);

if (ds != null && ds.Tables.Count >= 1 && ds.Tables[0].Rows.Count >= 1)
{
    //Debugg ds and you will see the number of records that affected in last update
}
Bharat
  • 5,869
  • 4
  • 38
  • 58
  • 1
    What's the point in wrapping such a simple single statement in a stored proc (I know some places have "only stored procedure" rules, but that's about DBAs having control issues.) – Richard Sep 22 '17 at 13:38
  • @Richard : only one, She needs to understand the SP based framework, check comments in question part..it can be helpfull for other SO.. – Bharat Sep 22 '17 at 13:43
  • 1
    SProcs only came up when you suggested them ("what exactly is a Stored Procedure"). – Richard Sep 22 '17 at 13:47
  • @Richard, Yes, that's true, but what I think is that SO is new, and she didn't even know about SP, and that's why I created that much mesh, I also know that Issue is in the parameters that she is passing but she can't check it because of inline query. maybe my answer can explain her a way of ADO.Net working pattern.. – Bharat Sep 22 '17 at 13:52
  • You're really just confusing absolutely everything by suggesting a stored proc when there was no need to. Stored Procs aren't magic solutions. Also, this catching an exception and returning null business is just gross. – mason Sep 22 '17 at 14:08