这个问题的确是需要注意的问题,Raymond对此进行了详细阐述:)
Comments
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;
Comments