插入一条记录并返回当前的ID(自增的ID)

#region 执行插入语句并且返回当前的ID /// <summary> /// 执行插入语句并且返回当前的ID /// </summary> /// <param name="strInsert"></param> /// <param name="paraInsert"></param> /// <param name="strTable">[YhkwebData].[dbo].[T_Message]</param> /// <returns></returns> private int ExecuteSql(string strInsert, System.Data.SqlClient.SqlParameter[] paramInsert, string strTable) { string connectionString = ConfigurationManager.ConnectionStrings["DataCenterConnectionString"].ToString(); using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { DbHelperSQL.PrepareCommand(cmd, conn,trans, strInsert, paramInsert); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText ="SELECT IDENT_CURRENT('"+strTable+"')"; int newID=int.Parse(cmd.ExecuteScalar().ToString()); trans.Commit(); return newID; } catch { trans.Rollback(); throw; } } } } #endregion

你可能感兴趣的:(插入一条记录并返回当前的ID(自增的ID))