引言
项目中遇到这么一个问题,在做数据库的插入操作时我同时还需要查出主键id,如果写两个方法固然可以,但是也有更简便的实现方式,下面分享给大家。
代码
<span style="font-size:18px;"> public int Add(B_0003Info entity)
{
try
{
Database db = DBHelper.CreateDataBase();
string Str = string.Format("insert into [B_0003Info]([DocumentNo],[DepartmentNo],[ConstraintName],[ProblemDescribe],[Solution],[IsSpecial],
[IsSolve],[ISClose],[IsDelete],[CreateDate]) values('{0}','{1}','{2}','{3}','{4}',{5},{6},{7},{8},'{9}');
<span style="color:#FF0000;">select @@IDENTITY"</span>, entity.DocumentNo, entity.DepartmentNo, entity.ConstraintName, entity.ProblemDescribe, entity.Solution, entity.IsSpecial,
entity.IsSolve, entity.ISClose, entity.IsDelete, entity.CreateDate);//添加相应sql语句
DbCommand cmd = db.GetSqlStringCommand(Str);
int id = Convert.ToInt32(db.ExecuteScalar(cmd));
if (id > 0)
{
UpdateConstraintStates(entity);
}
return id;
}
catch (Exception ex)
{
log4netHelper.WriteLog(typeof(B_0003InfoDAL), ex);
return 0;
}
}</span>
理解
大家在代码中看到select @@IDENTITY这行代码。作用就是查出插入行的主键id,然后通过return id就可以将其返回前端。删除和更新也同理,是不是很实用呢。
小结
做项目中应该多多总结这些干货,多多积累。才能在今后的项目中运用自如。