简体   繁体   English

C#更新和数据库集(datediff)在C#中无效,但在SQL Server中有效

[英]C# update and set of database (datediff) don't work when in C# but works if in SQL Server

I have searched for solutions but I can't find one; 我已经在寻找解决方案,但是找不到。 please help. 请帮忙。

I have this code fragment in C#: 我在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. 它没有在try块中显示消息框,也没有在catch块中显示消息框。

Thanks for helping :D 感谢您的帮助:D

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();
}

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). 因此,基本SP如下所示,我将在数据库(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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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