类代码:
#region "增加表的记录"
/// <summary>
/// 增加一条数据
/// </summary>
public int Insert(M_ProductType model,out int count)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into ProductType(");
strSql.Append("ParentID,boolid,QueryID,typename");
strSql.Append(")");
strSql.Append(" values (");
strSql.Append("" + model.ParentID + ",");
strSql.Append("" + model.BoolID + ",");
strSql.Append("'" + model.QueryID + "',");
strSql.Append("'" + model.Typename + "'");
strSql.Append(")");
strSql.Append(";select @@IDENTITY");
int result = DBAction.Count(strSql.ToString(),out count);
return result;
}
#endregion
红色那行是重点,还有就是参数里(蓝色那个)是用来接收刚插入值的ID。然后方法里的Count的方法是这样写的:
public static int Count(string sql,out int count)
{
SqlConnection cn = null;
try
{
cn = new SqlConnection(con);
cn.Open();
SqlCommand cmd = new SqlCommand(sql, cn);
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
count = 0;
return 0;
}
else
{
int rows = Int32.Parse(obj.ToString());
count = rows;
return rows;
}
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
if (cn != null)
{
cn.Close();
cn.Dispose();
}
}
}
在页面上调用 的方法是:
int count;
int result = dal.Add(model,out count);
这个count就是刚插入值的ID号了,还有就是千万不要给count赋初值不然会报错,