[英]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;
,這保證了在發生錯誤時回滾。
其他注意事項:
SqlParameter
上使用適當的類型、長度和精度,這將有助於提高性能。MessageBox
之類的東西阻塞線程。 記錄異常並在之后檢查。 或者更好的是,做我上面所做的並try/catch
連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.