在做三层架构的时候,特别是对表做查询的时候,有时候并不确定查询条件的个数,比如查询学生表:有可能只输入学号,或者姓名,或者性别,总之查询条件的参数个数并不确定,下面是我用List实现传值的代码:

附图如下:

在这里附上数据库的表结构:

CREATE TABLE Student(
        StuId        VARCHAR(6) PRIMARY KEY,
        StuName   VARCHAR(10) NOT NULL,
        MajorId     INT NOT NULL,
        Sex           VARCHAR(2) NOT NULL DEFAULT '男',
        Birthdate   SMALLDATETIME NOT NULL,
        Credit        FLOAT,
        Remark     VARCHAR(200)
)

------------------------------------------------------------------------------------------------

程序代码如下:

Model层----------------------------------------------包含两个类------------------------

------------------表的实体类Student-----------------

public class Student
    {
        private string stuId; 
        public string StuId
        {
            get { return stuId; }
            set { stuId = value; }
        }

private string stuName;

public string StuName

{

get { return stuName; }

set { stuName = value; }

}

private int majorId;

public int MajorId

{

get { return majorId; }

set { majorId = value; }

}

private string sex;

public string Sex

{

get { return sex; }

set { sex = value; }

}

private DateTime birthdate;

public DateTime Birthdate

{

get { return birthdate; }

set { birthdate = value; }

}

private float credit;

public float Credit

{

get { return credit; }

set { credit = value; }

}

private string remark;

public string Remark

{

get { return remark; }

set { remark = value; }

}

}

------------------Condition主要用于传递参数,这个类也可以定义在别的地方-------------------

public class Condition
    {
        public string paramName { get; set; }
        public string paramValue { get; set; }
        public ConditionOperate Operation { get; set; }

// 查询所用到的运算操作符
        public enum ConditionOperate : byte
        {
            Equal,           // 等于
            NotEqual,      // 不等于
            Like,             // 模糊查询
            Lessthan,      // 小于等于
            GreaterThan  // 大于
        }
    }

---------------------DAL层-----------------------------------------------------------------

------------------DBHelper类---------------------------------------------

public class DBHelper

{

private SqlConnection conn;

private SqlCommand cmd;

private SqlDataAdapter sda;

private DataSet ds;

public DBHelper()

{

conn = new SqlConnection(ConfigurationManager.ConnectionStrings["key"].ConnectionString);

}

// 不带参数的查询

public DataSet GetResult(string sql, CommandType type)

{

cmd = new SqlCommand(sql, conn);

sda = new SqlDataAdapter(cmd);

conn.Close();

ds = new DataSet();

sda.Fill(ds, "student");

return ds;

}

// 带参数的查询

public DataSet GetResult(string sql, CommandType type, params SqlParameter[] paras)

{

cmd = new SqlCommand(sql, conn);

if (type == CommandType.StoredProcedure)

{

cmd.CommandType = CommandType.StoredProcedure;

}

cmd.Parameters.AddRange(paras);

sda = new SqlDataAdapter(cmd);

conn.Close();

ds = new DataSet();

sda.Fill(ds, "student");

return ds;

}

}

-----------------------------对Student表操作类

public class StudenDAL

{

public DataSet GetStudent(List<Condition> condition)

{

DataSet ds = new DataSet();

DBHelper db = new DBHelper();

string sql = "select * from student";

// 如果带查询语句带参数

if (condition.Count > 0)

{

sql += SqlString(condition);

ds = db.GetResult(sql, CommandType.Text, SqlParas(condition));

}

else

{

ds = db.GetResult(sql, CommandType.Text);

}

return ds;

}

----------------------以下两个可以写成一个类,以便如果有多张表时,可以实现代码的复用----------------------------------

// 获取查询参数

public SqlParameter[] SqlParas(List<Condition> cond)

{

List<SqlParameter> paras = new List<SqlParameter>();

for (int i = 0; i < cond.Count; i++)

{

SqlParameter para = new SqlParameter("@" + cond[i].paramName, cond[i].paramValue);

if (cond[i].Operation == Condition.ConditionOperate.Like)

{

para.SqlValue = "%" + cond[i].paramValue + "%";

}

paras.Add(para);

}

return paras.ToArray();

}

// 获取SQL查询语句的where子句

public string SqlString(List<Condition> cond)

{

string sqlWhere = string.Empty;

List<string> where = new List<string>();

// 数组元素的顺序应该与ConditionOperate枚举值顺序相同

string[] operateType = { " = ", " <> ", " Like ", " <= ", " >= " };

for (int i = 0; i < cond.Count; i++)

{

int index = (int)cond[i].Operation;

where.Add(string.Format("{0}" + operateType[index] + "{1}", cond[i].paramName, "@" + cond[i].paramName));

}

sqlWhere = " where " + string.Join(" and ", where.ToArray());

return sqlWhere;

}

}

------------------------------BLL层---------------------------

public class StudentBLL
    {
        private readonly StudenDAL stuDal = new StudenDAL();
        public DataSet GetStudent(List<Condition> condition)
        {
            return stuDal.GetStudent(condition);
        }
    }

------------------------------UI层,查询按钮的单击事件-------------------------------------

protected void btnSearch_Click(object sender, EventArgs e)

{

Condition condition;

StudentBLL stu = new StudentBLL();

List<Condition> list = new List<Condition>();

if (txtId.Text!="")

{

condition = new Condition()

{

paramName = "stuId",

paramValue = txtId.Text,

Operation = Condition.ConditionOperate.Equal

};

list.Add(condition);

}

if (txtName.Text!="")

{

condition = new Condition()

{

paramName = "stuName",

paramValue = txtName.Text,

Operation = Condition.ConditionOperate.Equal

};

list.Add(condition);

}

if (txtSex.Text != "")

{

condition = new Condition()

{

paramName = "Sex",

paramValue = txtSex.Text,

Operation = Condition.ConditionOperate.Equal

};

list.Add(condition);

}

GridView1.DataSource = stu.GetStudent(list);

GridView1.DataBind();

}

ASP.NET三层架构之不确定查询参数个数的查询的更多相关文章

  1. Asp.Net 三层架构之泛型应用

    一说到三层架构,我想大家都了解,这里就简单说下,Asp.Net三层架构一般包含:UI层.DAL层.BLL层,其中每层由Model实体类来传递,所以Model也算是三层架构之一了,例外为了数据库的迁移或 ...

  2. asp.net三层架构 及其中使用泛型获取实体数据介绍

    asp.net中使用泛型获取实体数据可以发挥更高的效率,代码简洁方便,本例采用三层架构.首先在model层中定义StuInfo实体,然后在 DAL层的SQLHelper数据操作类中定义list< ...

  3. 新闻公布系统 (Asp.net 三层架构 )

    2012年度课程设计---新闻公布系统(小结)                                                                             ...

  4. ASP.NET三层架构的分析

    BLL   是业务逻辑层   Business   Logic   Layer DAL   是数据访问层   Data   Access   Layer ASP.NET的三层架构(DAL,BLL,UI ...

  5. ASP.NET三层架构项目创建流程

    1.进入VS2010,新建项目—>Visual C#—>Web—>ASP.NET空Web应用程序,如图所示: 2.在解决方案处右击—>新建项目—>Windows—> ...

  6. 三层架构的一点理解以及Dapper一对多查询

    1.首先说一下自己对三层架构的一点理解 论坛里经常说会出现喜欢面相对象的写法,所以使用EF的,我个人觉得他俩没啥关系,先别反对,先听听我怎么说吧. 三层架构,基本都快说烂了,但今天还是说三层架构:UI ...

  7. 初学者-asp.net三层架构

    一.概述: 通常意义上的三层架构就是将整个业务应用划分为:表现层(UI).业务逻辑层(BLL).数据访问层(DAL).区分层次的目的即为了“高内聚,低耦合”的思想.是一种总体设计的思想. 1.表现层( ...

  8. asp.net三层架构详解

    一.数据库 /*==============================================================*/ /* DBMS name:      Microsof ...

  9. asp.net三层架构详解(转)

    摘自:http://www.cnblogs.com/cresuccess/archive/2008/12/10/1351675.html 一.数据库             ,)   )     no ...

随机推荐

  1. Ember.js实现单页面应用程序

    1.1.1 摘要 单页应用程序 (SPA) 是加载单个HTML 页面并在用户与应用程序交互时动态更新该页面的Web应用程序. SPA使用AJAX和HTML5创建流畅且响应迅速的Web应用程序,不会经常 ...

  2. python面向对象随笔

    传送门:http://www.runoob.com/python/python-object.html

  3. Atitit  图像处理底色变红的解决

    Atitit  图像处理底色变红的解决 1.1. 原因  ImageIO  bug ,alpha通道应该在保存jpg的时候排除1 1.2. 解决,自己移除alpha通道即可1 2. Image sav ...

  4. Atitit 信用卡与会员卡(包括银行卡)的发展之路

    Atitit 信用卡与会员卡(包括银行卡)的发展之路 实现跨机构卡片内金额的流动解决方案 1.1. 财务卡片本质上都是会员卡1 1.2. 卡片的发展阶段1 2. 实现跨机构卡片内金额的流动解决方案(加 ...

  5. chrome开发总结(交互/权限/存储)-爬虫

    chrome开发总结(交互/权限/存储)-爬虫 [TOC] 标签(空格分隔): 杂乱之地 经过一翻折腾.还是选择了chrome来做爬虫.主要是为了解决一些ajax加载的问题以及代理的问题. 1.chr ...

  6. javascript中关于日期和时间的基础知识

    × 目录 [1]标准时间 [2]字符串 [3]闰年[4]月日[5]星期[6]时分秒 前面的话 在介绍Date对象之前,首先要先了解关于日期和时间的一些知识.比如,闰年.UTC等等.深入了解这些,有助于 ...

  7. java中同步嵌套引起的死锁事例代码

    /* 目的:自己写一个由于同步嵌套引起的死锁! 思路:多个线程在执行时,某一时刻,0-Thread绑定了LockA锁,1-Thread绑定了LockB锁! 当0-Thread要去绑定LockB锁时 和 ...

  8. CSS3入门之转换

    CSS3入门之转换 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !impor ...

  9. Oracle 11gR2静默安装 & 命令行安装

    静默安装 经常搭建Oracle测试环境,有时候觉得OUI(即图形界面)方式甚是繁琐,你得一步一步进行确认,所幸,Oracle支持静默安装.在我看来,它主要有两方面的好处:一.极大地提升了效率,尤其是批 ...

  10. 基于Metronic的Bootstrap开发框架经验总结(8)--框架功能总体界面介绍

    在前面介绍了一系列的<基于Metronic的Bootstrap开发框架经验总结>的随笔文章,随笔主要是介绍各个知识点的内容,对框架的总体性界面没有很好的阐述,本篇随笔主要介绍这个Boots ...