繁体   English   中英

SQLHelper Class - 插入/更新方法返回插入的 ID @@identity

[英]SQLHelper Class - Insert/Update method return inserted ID @@identity

我的应用程序有一个 SQL 助手 Class,一切正常,但在某些代码中,我需要使用 @@identity 获取插入的 ID,最好的方法是什么?

这是我在 SQL 助手 class 中的方法:

public static void InsertUpdate_Data(string sql, CommandType cmdType, params SqlParameter[] parameters)
        {
            using (SqlConnection connStr = new SqlConnection(ConnectionString))
            using (SqlCommand cmd = new SqlCommand(sql, connStr))
            {
                cmd.CommandType = cmdType;
                cmd.Parameters.AddRange(parameters);
                try
                {
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    //log to a file or Throw a message ex.Message;
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }

这就是我使用它的方式:

DBConn.InsertUpdate_Data("customer_add", CommandType.StoredProcedure,
               new SqlParameter[]
               {
                new SqlParameter("@name", txt_name.Text.Trim()),
                new SqlParameter("@gender", Gender_comb.Text),
                new SqlParameter("@b_o_date", DOBTimePicker1.Value ),
                new SqlParameter("@phone", Phone_txt.Text.Trim()),
                new SqlParameter("@address", string.IsNullOrEmpty(Location_txt.Text) ? (object)DBNull.Value : Location_txt.Text.Trim()),
                new SqlParameter("@note", string.IsNullOrEmpty(Note_txt.Text) ? (object)DBNull.Value : Note_txt.Text.Trim())
               }

还有什么是在某些代码中使用 SQL 事务的最佳方法。

谢谢你。

不要使用@@IDENTITY它是不可靠的

存储过程应该在紧跟插入之后的行上具有SELECT SCOPE_IDENTITY() 然后你可以使用提到的cmd.ExecuteScalar


对于交易,您有两种选择。

要么使用conn.BeginTransaction()并且不要忘记先打开连接,将事务添加到command.Transaction ,然后将事务放在using块中:

public static int InsertUpdate_Data(string sql, CommandType cmdType, params SqlParameter[] parameters)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(ConnectionString))
                {
                    conn.Open()
                    using (var tran = conn.BeginTransaction())
                    using (SqlCommand cmd = new SqlCommand(sql, connStr, tran))
                    {
                        cmd.CommandType = cmdType;
                        cmd.Parameters.AddRange(parameters);
                        var result = (int)cmd.ExecuteScalar();
                        tran.Commit();
                        return result;
                    }
                }
            }
            catch (SqlException ex)
            {
                //log to a file or Throw a message ex.Message;
                MessageBox.Show("Error: " + ex.Message);
                throw;
            }
        }

另一个可能更好的选择是使用BEGIN TRANSACTION; COMMIT TRANSACTION; 在程序中。 不要打扰TRY/CATCH/ROLLBACK ,只需放在程序的顶部SET XACT_ABORT ON; ,这保证了在发生错误时回滚。


其他注意事项:

  1. SqlParameter上使用适当的类型、长度和精度,这将有助于提高性能。
  2. 当连接打开时,不要MessageBox之类的东西阻塞线程。 记录异常并在之后检查。 或者更好的是,做我上面所做try/catch连接。

暂无
暂无

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

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