繁体   English   中英

无法在 .NET 4.0 中使用 ADO.NET 获取插入命令的记录 ID

[英]Unable to get record Id for Insert command using ADO.NET in .NET 4.0

我正在使用 NET Framework 4.0 Insert命令处理 ADO.NET。 我需要返回创建记录的主要内容。 我已经实现了以下代码,但得到了空值。 我想确保我得到正确的 ID 而不仅仅是最近创建的,因为它可能是多个用户同时尝试添加记录的情况

private bool InsertData()
    {
        bool isRecordCreated = false;

        try
        {
            using (SqlCommand cmd = new SqlCommand(InsertScript(), dbConnection))
            {
                
                cmd.Parameters.Add("@UserProfileStatus", SqlDbType.Int).Value = UserProfiles.UserProfileStatus;
                cmd.Parameters.Add("@UserProfileAccount", SqlDbType.VarChar).Value = UserProfiles.UserProfileAccount;
                cmd.Parameters.Add("@UserProfileTimeStamp", SqlDbType.DateTime).Value = UserProfiles.UserProfileTimeStamp;
                cmd.Parameters.Add("@UserProfileId", SqlDbType.Int).Direction = ParameterDirection.Output;

                dbConnection.Open();

                cmd.ExecuteNonQuery();

                string id = cmd.Parameters["@UserProfileId"].Value.ToString(); // need help here.....
            }              
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if (dbConnection != null)
            {
                dbConnection.Close();
            }
        }

        return isRecordCreated;
    }

    private string InsertScript()
    {
        string script = string.Empty;

        script = "INSERT INTO [dbo].[UserProfile]([UserProfileStatus],[UserProfileAccount],[UserProfileTimeStamp]) " +
                 "VALUES (@UserProfileStatus, @UserProfileAccount, @UserProfileTimeStamp)";

        return script;
    }

您只需要将这一行添加到您之前的脚本中

script = @"INSERT INTO [dbo].[UserProfile]([UserProfileStatus], 
               [UserProfileAccount],[UserProfileTimeStamp]) 
           VALUES (@UserProfileStatus, @UserProfileAccount,  
                   @UserProfileTimeStamp);
           SELECT SCOPE_IDENTITY();";

然后使用 ExecuteScalar 执行查询,删除 output 参数。 SCOPE_IDENTITY将返回在当前连接上生成的下一个 IDENTITY 值。 所以它将独立于其他用户正在做什么

int id = cmd.ExecuteScalar();

请注意脚本的第一部分是如何与添加分号的第二部分分开的。 这种技术被称为“ 批处理 Sql 语句”,并由 Sql 服务器支持

暂无
暂无

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

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