</pre><pre name="code" class="csharp"> class StudentDAL
{
public static int GetCount()
{
return (int)SqlHelper.ExecuteScalary("select count(*) from T_Student ");
}
public static void DeleteById(long id)
{
SqlHelper.ExecuteNonQuery("delete from T_Student where Id = @Id ",
new SqlParameter("@Id", id));
}
//如果列非常多,参数机会非常多,要把参数封装到Model中
public static object ToDBValue(object value)
{
if (value == null)
{
return DBNull.Value;
}
else return value;
}
public static void Insert(Student student)
{
//object age;
//if (student.Age == null )
//{
// age = DBNull.Value;
//}
//else
//{
// age = student.Age;
//}
//object name;
//if (student.Name == null)
//{
// name = DBNull.Value;
//}
//else
//{
// name = student.Name;
//}
SqlHelper.ExecuteNonQuery(@"insert into T_Student (Name,Age,Height)
values (@Name,@Age,@Height)",
new SqlParameter("@Name", ToDBValue (student.Name )),
new SqlParameter("@Age", ToDBValue(student .Age )),
new SqlParameter("@Height", student.Height));
}
public static object FromDBValue ( object value )
{
if (value == DBNull.Value)
{
return null;
}
else
return value;
}
//DAL不要返回Data Table dataRow等ADO.NET的类
public static Student GetById(long Id)
{
DataTable table = SqlHelper.ExecuteDataTables("select * from T_Student where Id = @Id",
new SqlParameter("@Id", Id));
if (table.Rows.Count <= 0 )
{
return null;
}
else if (table .Rows .Count >1)
{
throw new Exception("Id 重复");
}
else
{
DataRow row = table.Rows[0];
Student student = new Student();
student.Id = (long)row["Id"];
student.Name = (string)FromDBValue(row["Name"]);
student.Age = (int ?)FromDBValue(row["Age"]);
student.Height = (int)row["Height"];
return student ;
}
}
}
class Student
{
//对于可空列。要注意 int? 的问题
public long Id { get; set; }
public string Name{get ;set ;}
public int? Age {get ; set ;}
public decimal? Height { get; set; }
}