SqlParameter[] 数组 sql语句中参数的填充的通用访问类的使用方法

  • Post author:
  • Post category:其他


//1.定义通用访问类的方法

public static SqlDataReader GetReader(string sql,SqlParameter [] para)

{


//实例化conn

SqlConnection conn = new SqlConnection(connString);

//实例化cmd

SqlCommand cmd = new SqlCommand(sql, conn);

try

{


conn.Open();

//把参数数组添加到Command对象中

cmd.Parameters.AddRange(para);

//返回SqlDataReader

return cmd.ExecuteReader(CommandBehavior.CloseConnection);

}

catch (Exception ex)

{

            throw ex;
        }
    }

//2.调用通用访问类的方法

private void btnSelect_Click(object sender, EventArgs e)

{


//实例化DataSet

DataSet ds = new DataSet();

// 定义查询语句

string sql = “SELECT SNO, SName, Gender, Birthday, Mobile, Email, HomeAddress, PhotoPath FROM Student where SNO LIKE @SNO AND SName Like @SName AND Mobile Like @Mobile”;//

if (cmbSex.Text.Contains(“女”))

{


sql += ” and Gender=‘女’ “;

}

else if (cmbSex.Text.Contains(“男”))

{


sql += ” and Gender=‘男’ “;

}

//对数组中的参数赋值

SqlParameter[] para = new SqlParameter[]

{


new SqlParameter(”@SNO”, txtID.Text.Trim()+”%”),

new SqlParameter(“@SName”, txtName.Text.Trim()+”%”),

new SqlParameter(“@Mobile”, txtMoblie.Text.Trim()+ “%”),

};

//实例化 SqlDataReader 接收 通用访问类的值

SqlDataReader sdr = GetReader(sql,para);

//为表赋值表名称

ds.Tables.Add(“Student”);

//加载数据到DataSet的Student的Table中

ds.Tables[“Student”].Load(sdr);

//展示数据

dgvStudent.DataSource = null;

dgvStudent.DataSource = ds.Tables[“Student”];

    }



版权声明:本文为cuibaoming原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。