【问题标题】:Unable to insert data in database - No exception thrown无法在数据库中插入数据 - 没有抛出异常
【发布时间】:2020-07-16 20:50:47
【问题描述】:

我正在尝试使用存储过程将数据插入[AdventureWorks2017].[HumanResources].[Employee]。我已经测试了存储过程,它适用于我使用 C# 代码提供的值。

当我尝试对稍有不同的值(相同格式)执行相同操作时,代码不会引发异常或错误,但值不会反映在数据库中。我试过调试,所有变量都有要插入的值,并且与数据库的连接也打开了。

{
    Employee employee = new Employee();
    DateTime birthDate = new DateTime(1962, 07, 21);
    DateTime hireDate = new DateTime(2000, 01, 01);
    employee.RegisterEmployee("EM", 0, "Mr.", "Rakesh", "null", "Tripathi", "null", 0, "null", "null", "667567", "adventure-works\rakesh", "null", "Vice President of Engineering", birthDate, 'M', 'M', hireDate, 1, 100, 20, 1);
}

public int RegisterEmployee(string personType, int nameStyle, string title, string firstName, string middleName, string lastName, string suffix,
    int emailPromotion, string additionalContactInfo, string demographics, string nationalIdNumber, string loginId, string organizationNode, string jobtitle,
    DateTime dateOfBirth, char maritalStatus, char gender, DateTime hireDate, int salaried, int vacationHours, int sickLeaveHours, int currentFlag )
{
    SqlCommand sqlCommand;

    try 
    {
        this.ConnectToDatabase();
        this.sqlConnection.Open();

        string commandText = "usp_RegisterNewEmployee";
        sqlCommand = new SqlCommand(commandText, this.sqlConnection);
        sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

        sqlCommand.Parameters.AddWithValue("@PersonType", personType);
        sqlCommand.Parameters.AddWithValue("@NameStyle", nameStyle);
        sqlCommand.Parameters.AddWithValue("@Title", title);
        sqlCommand.Parameters.AddWithValue("@FirstName", firstName);
        sqlCommand.Parameters.AddWithValue("@LastName", lastName);
        sqlCommand.Parameters.AddWithValue("@JobTitle", jobtitle);
        sqlCommand.Parameters.AddWithValue("@BirthDate", dateOfBirth);
        sqlCommand.Parameters.AddWithValue("@EmailPromotion", emailPromotion);
        sqlCommand.Parameters.AddWithValue("@MaritalStatus",maritalStatus);
        sqlCommand.Parameters.AddWithValue("@Gender", gender);
        sqlCommand.Parameters.AddWithValue("@HireDate", hireDate);
        sqlCommand.Parameters.AddWithValue("@SalariedFlag", salaried);
        sqlCommand.Parameters.AddWithValue("@VacationHours", vacationHours);
        sqlCommand.Parameters.AddWithValue("@SickLeaveHours", sickLeaveHours);
        sqlCommand.Parameters.AddWithValue("@CurrentFlag",currentFlag);
        sqlCommand.Parameters.AddWithValue("@NationalIdNumber", nationalIdNumber);
        sqlCommand.Parameters.AddWithValue("@LoginID", loginId);

        if (middleName == "null")
            sqlCommand.Parameters.AddWithValue("@MiddleName", DBNull.Value);
        else
            sqlCommand.Parameters.AddWithValue("@MiddleName", middleName);

        if (suffix == "null")
            sqlCommand.Parameters.AddWithValue("@Suffix", DBNull.Value);
        else
            sqlCommand.Parameters.AddWithValue("@Suffix", suffix);

        if (additionalContactInfo == "null")
            sqlCommand.Parameters.AddWithValue("@AdditionalContactInfo", DBNull.Value);
        else
            sqlCommand.Parameters.AddWithValue("@AdditionalContactInfo", additionalContactInfo);

        if (demographics == "null")
            sqlCommand.Parameters.AddWithValue("@Demographics", DBNull.Value);
        else
            sqlCommand.Parameters.AddWithValue("@Demographics", demographics);

        if (organizationNode == "null")
            sqlCommand.Parameters.AddWithValue("@OrganizationNode", DBNull.Value);
        else
            sqlCommand.Parameters.AddWithValue("@OrganizationNode", organizationNode);

        SqlParameter BusinessEntityIdOutput = new SqlParameter("@BusinessEntityIdOutput", System.Data.SqlDbType.Int);
        BusinessEntityIdOutput.Direction = System.Data.ParameterDirection.Output;
        sqlCommand.Parameters.Add(BusinessEntityIdOutput);

        SqlParameter returnValue = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        returnValue.Direction = System.Data.ParameterDirection.ReturnValue;
        sqlCommand.Parameters.Add(returnValue);

        int result = sqlCommand.ExecuteNonQuery();
        Console.WriteLine("total rows affected:", result);
        int businessEntityId = Convert.ToInt32(BusinessEntityIdOutput.Value);
        Console.WriteLine("Business entity id: " + businessEntityId);
    
    }
    catch (Exception e)
    {
        Console.WriteLine("Some error occurred...");
        Console.WriteLine(e.Message);
    }
    finally
    {
        this.sqlConnection.Close();
    }
    return 0;
}

我试图从123 中找到解决方案,但这些不适用于我的情况。

下面是我用来插入值的存储过程。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[usp_RegisterNewEmployee]
(
    /*Parameters required for person*/
    @PersonType         [nchar](2),
    @NameStyle          [dbo].[NameStyle] = 0,
    @Title              [nvarchar](8),
    @FirstName          [dbo].[Name],
    @MiddleName         [dbo].[Name],
    @LastName           [dbo].[Name],
    @Suffix             [nvarchar](10),
    @EmailPromotion     [int],
    @AdditionalContactInfo [xml] = NULL,
    @Demographics       [xml] = NULL,

    /*Parameters required for Employee*/
    @NationalIdNumber   [nvarchar](15),
    @LoginID            [nvarchar](256),
    @OrganizationNode   [hierarchyid],
    @JobTitle           [nvarchar](50),
    @BirthDate          [date],
    @MaritalStatus      [nchar],
    @Gender             [nchar],
    @HireDate           [date],
    @SalariedFlag       [dbo].[Flag],
    @VacationHours      [smallint], 
    @SickLeaveHours     [smallint],
    @CurrentFlag        [dbo].[Flag],
    @BusinessEntityIdOutput INT OUT
)
AS 
SET NOCOUNT ON;
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION
                DECLARE @BusinessEntityID INT
        /* Enter new business entity id column in Person.BusinessEntity table */
                INSERT INTO [AdventureWorks2017].[Person].[BusinessEntity] 
VALUES (NEWID(), GETDATE());
                SELECT @BusinessEntityID = SCOPE_IDENTITY();
                SET @BusinessEntityIdOutput = @BusinessEntityID;

            /* Register the same person in Person.Person table */
              INSERT INTO [AdventureWorks2017].[Person].[Person]
              (
                [BusinessEntityID], 
                [PersonType],
                [NameStyle], 
                [Title], 
                [FirstName],
                [MiddleName], 
                [LastName], 
                [Suffix], 
                [EmailPromotion], 
                [AdditionalContactInfo],
                [Demographics], 
                [rowguid], 
                [ModifiedDate]
                ) VALUES 
                (
                    @BusinessEntityID,
                    @PersonType,
                    @NameStyle, 
                    @Title,
                    @FirstName,
                    @MiddleName,
                    @LastName,
                    @Suffix,
                    @EmailPromotion,
                    @AdditionalContactInfo, 
                    @Demographics,
                    NEWID(),
                    GETDATE()
                )

            /* Input the new row in the HumanResources.Employees table */
            INSERT INTO [HumanResources].[Employee]
            (
                [BusinessEntityID],
                [NationalIDNumber],
                [LoginID],
                [OrganizationNode],
                [JobTitle],
                [BirthDate],
                [MaritalStatus],
                [Gender],
                [HireDate],
                [SalariedFlag],
                [VacationHours],
                [SickLeaveHours],
                [CurrentFlag],
                [rowguid],
                [ModifiedDate]
            )
            VALUES
           (
                @BusinessEntityID,
                @NationalIdNumber,
                @LoginID, 
                @OrganizationNode,
                @JobTitle,
                @BirthDate,
                @MaritalStatus,
                @Gender,
                @HireDate,
                @SalariedFlag,
                @VacationHours,
                @SickLeaveHours,
                @CurrentFlag,
                NEWID(),
                GETDATE()
            )
        COMMIT
        --RETURN @BusinessEntityIdOutput
    END TRY
    BEGIN CATCH
        ROLLBACK;
        RETURN -99
    END CATCH
END

【问题讨论】:

  • 那么哪些值有效,哪些值无效?
  • 我强烈建议您将所有AddWithValue 替换为Add,并使用正确的数据类型自己构建SqlParameter。使用AddWithValue时有很多problems
  • 我们可能还需要查看您的 SP 代码。
  • 一些一般性建议: 1. 将RegisterEmployee 更改为接受一个类(模型)并拥有现在有多个方法参数的属性。示例:public class EmployeeModel { public string Title {get; set; } }。 2.不要用"null"代替`null',那也是自找麻烦。 3. 对诸如 personType 之类的值可能仅限于特定子集的事物使用枚举或其他约束。最后不要使用“AddWithValue”,而是使用 Add 并包括数据类型和长度(如果适用)。
  • 完全不相关,但是,您的结果将始终为 0。

标签: c# sql-server ado.net


【解决方案1】:

看来存储过程正在更新 2 个表。

我将 try...catch 移至您与用户交流的 UI 代码。

连接不仅需要关闭,还需要处理以释放非托管对象。 using 块即使有错误也会处理这个问题。 命令也需要被释放。

下面的代码演示了如何将.Add 方法用于参数。 Sql Server 中的Bit 字段映射到.net 中的Boolean@AdditionalContactInfo@DemographicsXML 类型,但因为它们在您的代码中为空。我不会担心的。您似乎没有使用 2 out 参数,因为它们不需要值,我认为我们不需要包含它们。它们可能在存储过程内部使用。

除非存储过程为rowguid 提供值(可能是),否则您必须提供它。 ModifiedDate 也可能在存储过程中处理。这两个字段在 Employee 表中都不为空。

    private void OPCode()
    {
        Employee employee = new Employee();
        DateTime birthDate = new DateTime(1962, 07, 21);
        DateTime hireDate = new DateTime(2000, 01, 01);
        try
        { 
        int retval = employee.RegisterEmployee("EM", 0, "Mr.", "Rakesh", "null", "Tripathi", "null", 0, "null", "null", "667567", "adventure-works\rakesh", "null", "Vice President of Engineering", birthDate, 'M', 'M', hireDate, 1, 100, 20, 1);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
     }

public class Employee
{

    private string ConStr = "Your connection string";

    public int RegisterEmployee(string personType, int nameStyle, string title, string firstName, string middleName, string lastName, string suffix,
        int emailPromotion, string additionalContactInfo, string demographics, string nationalIdNumber, string loginId, string organizationNode, string jobtitle,
        DateTime dateOfBirth, char maritalStatus, char gender, DateTime hireDate, int salaried, int vacationHours, int sickLeaveHours, int currentFlag)
        {
            int result;
            using (SqlConnection cn = new SqlConnection(ConStr))
             using (SqlCommand  cmd = new SqlCommand("usp_RegisterNewEmployee", cn))
              {
                cmd.Parameters.Add("@PersonType", SqlDbType.NVarChar, 2).Value = personType;
                cmd.Parameters.Add("@NameStyle", SqlDbType.Bit).Value = Convert.ToBoolean(nameStyle);
                cmd.Parameters.Add("@Title", SqlDbType.NVarChar, 8).Value = title;
                cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = firstName;
                cmd.Parameters.Add("@MiddleName", SqlDbType.NVarChar, 50);
                cmd.Parameters.Add("@LastName", SqlDbType.NVarChar,50).Value = lastName;
                cmd.Parameters.Add("@JobTitle", SqlDbType.NVarChar,50).Value = jobtitle;
                cmd.Parameters.Add("@BirthDate", SqlDbType.Date).Value = dateOfBirth;
                cmd.Parameters.Add("@EmailPromotion", SqlDbType.Int).Value = emailPromotion;
                cmd.Parameters.Add("@MaritalStatus", SqlDbType.NVarChar,1).Value = maritalStatus;
                cmd.Parameters.Add("@Gender", SqlDbType.NVarChar,1).Value = gender;
                cmd.Parameters.Add("@HireDate", SqlDbType.Date).Value = hireDate;
                cmd.Parameters.Add("@SalariedFlag", SqlDbType.Bit).Value = Convert.ToBoolean(salaried);
                cmd.Parameters.Add("@VacationHours", SqlDbType.SmallInt).Value = vacationHours;
                cmd.Parameters.Add("@SickLeaveHours", SqlDbType.SmallInt).Value = sickLeaveHours;
                cmd.Parameters.Add("@CurrentFlag", SqlDbType.Bit).Value = Convert.ToBoolean(currentFlag);
                cmd.Parameters.Add("@NationalIdNumber", SqlDbType.NVarChar,15).Value = nationalIdNumber;
                cmd.Parameters.Add("@LoginID", SqlDbType.NVarChar,256).Value = loginId;
                cmd.Parameters.Add("@Suffix", SqlDbType.NVarChar, 10);
                cmd.Parameters.Add("@AdditionalContactInfo", SqlDbType.Xml);
                cmd.Parameters.Add("@Demographics", SqlDbType.Xml);
                cmd.Parameters.Add("@OrganizationNode", SqlDbType.NVarChar, 4000);
                cmd.Parameters.Add("@BusinessEntityIdOutput", SqlDbType.Int);
                cmd.Parameters["@BusinessEntityIdOutput"].Direction = ParameterDirection.Output;
                cmd.Parameters.Add("@ReturnValue", SqlDbType.Int);
                cmd.Parameters["@ReturnValue"].Direction = ParameterDirection.Output;
                    

               if (middleName == "null")
                    cmd.Parameters["@MiddleName"].Value = DBNull.Value;
                else
                    cmd.Parameters["@MiddleName"].Value = middleName;

                if (suffix == "null")
                    cmd.Parameters["@Suffix"].Value = DBNull.Value;
                else
                    cmd.Parameters["@Suffix"].Value = suffix;

                if (additionalContactInfo == "null")
                    cmd.Parameters["@AdditionalContactInfo"].Value = DBNull.Value;
                else
                   cmd.Parameters["@AdditionalContactInfo"].Value = additionalContactInfo;

                if (demographics == "null")
                    cmd.Parameters["@Demographics"].Value = DBNull.Value;
                else
                    cmd.Parameters["@Demographics"].Value = demographics;

                if (organizationNode == "null")
                    cmd.Parameters["@OrganizationNode"].Value = DBNull.Value;
                else
                    cmd.Parameters["@OrganizationNode"].Value = organizationNode;

                result = cmd.ExecuteNonQuery();
            }
                return result;
        }
}

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多