DAL层(增删改查方法)
- 创建DAL层使用类库
- 在DAL层创建类对应Model层(ps:起名方式 Model类名后加Service)
- 在DAL层添加引用: Model System.Configuration System.Data System.Data.SqlClient
使用某些引用时 先在解决方案资源管理器DAL层下的引用添加(右键 添加引用)
- 创建类后检查是否具有public属性 没有要手动加上 不然无法调用
- 查询方法(return SQLHelp的查询方法)
仅全部 Select() -> DataTable 或 List
public static DataTable Select() { string sql = "select * from ProductCategory"; return SQLHelp.Qurey(sql); }
仅部分 Select(条件) 主键id 登录 ->对象
public static DataTable Select(id) { string sql = "select * from ProductCategory where id="+id; return SQLHelp.Qurey(sql); }
部分+全部 Select(带默认值的条件) 前提:->DataTable 或 List (ps:模糊匹配使用like)
public static DataTable Select(int id = 0, string name = "") { string sql = "select * from ProductCategory,Product where ProductCategory.Id=Product.CategoryId"; if (id != 0) { sql += " and Product.CategoryId=" + id; } if (name != "") { sql += " and ProductName like '%" + name + "%'"; } return SQLHelp.Qurey(sql); }
-
删除方法(return SQLHelp的非查询方法)
调用NonQuery方法,返回int Delete(主键/对象)
public static int Delete(int id) { var sql = "delete from Product where Id=" + id; return DBHelp.NoQurey(sql); }
-
添加方法(return SQLHelp的非查询方法)
调用NonQuery方法,返回int Insert(实体对象)
SQL语法: insert into task values('{0}','{1}',getdate(),1,null,'{2}')
优先写死:使用固定值及SQL函数
public static int Inset(Task task) { string sql = string.Format("insert into Task values({0},'{1}',default,1,null,{2})", task.TaskPriority, task.Content, task.ProjectID); return DBHelp.NoQuery(sql); }
-
修改方法(return SQLHelp的非查询方法)
调用NonQuery方法,返回int Update(实体对象)
SQL语法: update task set TaskState=2,FinishedTime=getdate() where TaskID={0}
仅对需要修改的属性赋值,不需要修改的直接忽略 优先写死:使用固定值及SQL函数
public static int Update(int pid) { string sql = "update Task set TaskState=2,FinishedTime=getdate() where TaskID=" + pid; return DBHelp.NoQuery(sql); }
-
根据ID查询(ps:在使用获取原数据时使用 return SQLHelp的查询方法 )
调用Query方法 返回实体对象 Select(int id) 使用主键ID获取所有数据
使用sql语句把查询到的数据保存在表类型中
判断该表里是否有数据 如果没有 return null 如果有则 return 一个新对象保存数据
public static Product Select(int id) { string sql = "select * from Product where Id=" + id; DataTable dt = DBHelp.Qurey(sql); if (dt.Rows.Count < 1) { return null; } else { DataRow row = dt.Rows[0]; return new Product() { Id = Convert.ToInt32(row["Id"]), ProductName = Convert.ToString(row["ProductName"]), MarketPrice = Convert.ToInt32(row["MarketPrice"]), SellingPrice = Convert.ToInt32(row["SellingPrice"]), CategoryId = Convert.ToInt32(row["CategoryId"]), Introduction = Convert.ToString(row["Introduction"]), IsOnSale = Convert.ToInt32(row["IsOnSale"]), Addtime = Convert.ToDateTime(row["AddTime"]) }; } }
-
最后注意用///对每个方法添加注释