在我们写程序的时候,特别是数据库应用程序的时候,经常会遇到这样的情况:对于一个给定的表,写出这个表对应的类(用一句时髦的话说是实现业务实体类),类的数据成员是所有的字段,并且类含有该表的添加修改删除等操作。还有,对于一个给定的存储过程,要完成根据存储过程存取数据或别的数据库操作。如下代码就是我们通常要完成的:
1.表的业务实体化
private int iId ;
public int Id
{
get
{
return iId ;
}
set
{
iId = value ;
}
}
private string strName ;
public string Name
{
get
{
return strName ;
}
set
{
strName = value ;
}
}
private string strCode ;
public string Code
{
get
{
return strCode ;
}
set
{
strCode = value ;
}
}
private string strDescription ;
public string Description
{
get
{
return strDescription ;
}
set
{
strDescription = value ;
}
}
private int iFatherid ;
public int Fatherid
{
get
{
return iFatherid ;
}
set
{
iFatherid = value ;
}
}
private int iType ;
public int Type
{
get
{
return iType ;
}
set
{
iType = value ;
}
}
private int iUserId ;
public int UserId
{
get
{
return iUserId ;
}
set
{
iUserId = value ;
}
}
ublic bool Add()
{
SqlConnection conn = SqlConn.Instance().Connection ;
string strSql = "insert into book(id, Name, Code, Description, Fatherid, Type, UserId)"
+"values(@id, @Name, @Code, @Description, @Fatherid, @Type, @UserId)" ;
SqlCommand command = new SqlCommand(strSql,conn) ;
command.Parameters.Add("@id",SqlDbType.Int ) ;
command.Parameters["@id"].value = iId ;
command.Parameters.Add("@Name",SqlDbType.NVarChar ,50) ;
if (strName!= null )
command.Parameters["@Name"].value = strName ;
else
command.Parameters["@Name"].value = DBNull.value ;
command.Parameters.Add("@Code",SqlDbType.NVarChar ,255) ;
if (strCode!= null )
command.Parameters["@Code"].value = strCode ;
else
command.Parameters["@Code"].value = DBNull.value ;
command.Parameters.Add("@Description",SqlDbType.NVarChar ,255) ;
if (strDescription!= null )
command.Parameters["@Description"].value = strDescription ;
else
command.Parameters["@Description"].value = DBNull.value ;
command.Parameters.Add("@Fatherid",SqlDbType.Int ) ;
command.Parameters["@Fatherid"].value = iFatherid ;
command.Parameters.Add("@Type",SqlDbType.Int ) ;
command.Parameters["@Type"].value = iType ;
command.Parameters.Add("@UserId",SqlDbType.Int ) ;
command.Parameters["@UserId"].value = iUserId ;
try
{
conn.Open() ;
command.ExecuteNonQuery() ;
return true ;
}
catch(Exception e)
{
throw(new Exception("Error in the Database"+e.Message)) ;
}
finally
{
conn.Close() ;
}
}
public bool Modify()
{
SqlConnection conn = SqlConn.Instance().Connection ;
string strSql ="update book set id = @id, Name = @Name, Code = @Code, Description = @Description, Fatherid = @Fatherid, Type = @Type, UserId = @UserId "
+ " where id =@id " ;
SqlCommand command = new SqlCommand(strSql,conn) ;
command.Parameters.Add("@id",SqlDbType.Int ) ;
command.Parameters["@id"].value = iId ;
command.Parameters.Add("@Name",SqlDbType.NVarChar ,50) ;
command.Parameters["@Name"].value = strName ;
command.Parameters.Add("@Code",SqlDbType.NVarChar ,255) ;
command.Parameters["@Code"].value = strCode ;