简体   繁体   English

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

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

I have an SQL helper Class for my application, everything works nice as it should be, but in some code, I need to get the inserted ID using @@identity, what is the best way to do this??我的应用程序有一个 SQL 助手 Class,一切正常,但在某些代码中,我需要使用 @@identity 获取插入的 ID,最好的方法是什么?

Here is My method in my SQL helper class:这是我在 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);
                }
            }
        }

And this is how I use it:这就是我使用它的方式:

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

And also what is the best way to use SQL transactions in some code.还有什么是在某些代码中使用 SQL 事务的最佳方法。

Thank you.谢谢你。

Don't use @@IDENTITY , it's unreliable .不要使用@@IDENTITY它是不可靠的

The stored procedure should have, on the line immediately following the insert, SELECT SCOPE_IDENTITY() .存储过程应该在紧跟插入之后的行上具有SELECT SCOPE_IDENTITY() Then you can use cmd.ExecuteScalar as mentioned.然后你可以使用提到的cmd.ExecuteScalar


For transactions, you have two options.对于交易,您有两种选择。

Either use conn.BeginTransaction() and don't forget to open the connection first, add transaction to command.Transaction , and put the transaction in a using block:要么使用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;
            }
        }

The other, possibly better, option is to use BEGIN TRANSACTION;另一个可能更好的选择是使用BEGIN TRANSACTION; and COMMIT TRANSACTION;COMMIT TRANSACTION; in the procedure.在程序中。 Don't bother with TRY/CATCH/ROLLBACK , just put at the top of the procedure SET XACT_ABORT ON;不要打扰TRY/CATCH/ROLLBACK ,只需放在程序的顶部SET XACT_ABORT ON; , this guarantees a rollback on the event of an error. ,这保证了在发生错误时回滚。


Other notes:其他注意事项:

  1. Use proper types, length and precision on your SqlParameter s, it will help with performance.SqlParameter上使用适当的类型、长度和精度,这将有助于提高性能。
  2. Do not block the thread with things like MessageBox while the connection is open.当连接打开时,不要MessageBox之类的东西阻塞线程。 Log the exception and check it after.记录异常并在之后检查。 Or better, do what I did above and try/catch around the connection.或者更好的是,做我上面所做try/catch连接。

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

相关问题 从插入/更新查询中获取最后插入的ID返回 - Get last inserted ID return from a insert/update query 获取 controller 中的标识值以进行 INSERT(执行插入命令并在 Sql 中返回插入的 Id) - Get an identity value in a controller for INSERT (Execute Insert command and return inserted Id in Sql) 执行插入命令,返回插入的Id在Sql - Execute Insert command and return inserted Id in Sql 如何在MVC中插入数据并使用Dapper返回插入的标识? - How to insert data and return inserted identity with Dapper in MVC? 如何使用 Dapper 执行插入和返回插入的标识? - How do I perform an insert and return inserted identity with Dapper? 带有SqlHelper类的SqlBulkCopy - SqlBulkCopy with SqlHelper class NHibernate:插入后需要使用@@ identity更新对象ID - NHibernate: need to update object ID with @@identity after insert 如何在WCF + EF POCO解决方案中返回插入的ID(标识列)? - How can I return the inserted id (Identity column) in a WCF + EF POCO solution? Xamarin.Android SQLite SQLiteConnection.Insert不返回插入对象的ID - Xamarin.Android SQLite SQLiteConnection.Insert does not return inserted object's ID 如何在C#中使用一个命令将条目插入SQL Server数据库并返回包含主键标识的已插入列? - How do I insert an entry into a SQL Server database and return inserted columns including primary key identity with one command in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM