262008
 

Two methods.

Method 1、

string sql=”insert into………………”;
string sql2 = “select @@identity as ‘lastid'”;
            try
            {
                OpenConnection();
                SqlCommand=objSqlCommand = new SqlCommand(sql, objSqlConnection);
                objSqlCommand.ExecuteNonQuery();
                SqlDataAdapter=objSqlDataAdapter = new SqlDataAdapter(sql2, objSqlConnection);
                DataSet=objDataSet = new DataSet();
                objSqlDataAdapter.Fill(objDataSet, “identity”);
                String num = objDataSet.Tables[“identity”].Rows[0][“lastid”].ToString();
                CloseConnection();
                return int.Parse(num);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(“查询ID出错n” + ex.Message);
            }

Methods 2、(From CSDN)

if you are using ms sql server

sqlcommand.CommandText = “INSERT INTO sometable (filed1) VALUES (@filed1);”
+” SELECT @ID = @@identity “;
sqlcommand.Parameter.Add(“@field1″, …);

sqlcommand.Parameter.Add(“@ID”, SqlDbType.Int, 4).Direction = ParameterDirection.Output;
sqlcommand.ExecuteNonQuery();
int id = cmd.Parameters[“@ID”].Value;

 Posted by at 11:44 上午  Tagged with:

  One Response to “如何在C#中获取新插入的identity列值”

  1. 728146 641188wohh precisely what I was seeking for, thankyou for putting up. 270785

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>