C#参数化SQL查询

//写一个存储过程
ALTER PROCEDURE dbo.Infosearch

    (
    @bmid smallint = null,
    @xm varchar(10)=null,
    @xb varchar(10)=null,
    @strage smallint=null,
    @endage smallint=null,
    @zzmm varchar(10)=null,
    @xl varchar(10)=null,
    @zw varchar(10)=null
    )

AS
    /* SET NOCOUNT ON */
    declare @sql varchar(100)
    if @bmid is not null
    begin
        set @sql=‘ where 部门ID=‘+Convert(varchar(10),@bmid)
    end

    if @xm is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 姓名like‘+@xm
        else set @sql=‘ where 姓名like‘+@xm
    end

    if @xb is not null
    begin
        if    @sql is not null
            set @[email protected]+‘ and 性别=‘+@xb
        else set @sql=‘ where 性别=‘+@xb
    end

    if @strage is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 年龄between ‘+Convert(varchar(10),@strage)
        else set @sql=‘ where 年龄between ‘+Convert(varchar(10),@strage)
    end

    if @endage is not null
    begin
        set @[email protected]+‘ and ‘+Convert(varchar(10),@endage)
    end

    if @zzmm is not null
    begin
        if @sql is not null
             set @[email protected]+‘ and 政治面貌=‘+@zzmm
        else set @sql=‘ where 政治面貌=‘+@zzmm
    end

    if @xl is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 学历=‘+@xl
        else set @sql=‘ where 学历=‘+@xl
    end

    if @zw is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 职位=‘+@zw
        else set @sql=‘ where 职位=‘+@zw
    end

    exec(‘select 职工号,姓名,性别,年龄,学历,婚姻状况,政治面貌from yuangong‘+@sql)
    RETURN

ALTER PROCEDURE dbo.Infosearch

    (
    @bmid smallint = null,
    @xm varchar(10)=null,
    @xb varchar(10)=null,
    @strage smallint=null,
    @endage smallint=null,
    @zzmm varchar(10)=null,
    @xl varchar(10)=null,
    @zw varchar(10)=null
    )

AS
    /* SET NOCOUNT ON */
    declare @sql varchar(100)
    if @bmid is not null
    begin
        set @sql=‘ where 部门ID=‘+Convert(varchar(10),@bmid)
    end

    if @xm is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 姓名like‘+@xm
        else set @sql=‘ where 姓名like‘+@xm
    end

    if @xb is not null
    begin
        if    @sql is not null
            set @[email protected]+‘ and 性别=‘+@xb
        else set @sql=‘ where 性别=‘+@xb
    end

    if @strage is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 年龄between ‘+Convert(varchar(10),@strage)
        else set @sql=‘ where 年龄between ‘+Convert(varchar(10),@strage)
    end

    if @endage is not null
    begin
        set @[email protected]+‘ and ‘+Convert(varchar(10),@endage)
    end

    if @zzmm is not null
    begin
        if @sql is not null
             set @[email protected]+‘ and 政治面貌=‘+@zzmm
        else set @sql=‘ where 政治面貌=‘+@zzmm
    end

    if @xl is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 学历=‘+@xl
        else set @sql=‘ where 学历=‘+@xl
    end

    if @zw is not null
    begin
        if @sql is not null
            set @[email protected]+‘ and 职位=‘+@zw
        else set @sql=‘ where 职位=‘+@zw
    end

    exec(‘select 职工号,姓名,性别,年龄,学历,婚姻状况,政治面貌from yuangong‘+@sql)
    RETURN
 //判断参数是否为空来决定怎样拼接查询语句

如果是多条件查询的话
存储过程里面就一个参数就够了

这个参数是不定条件查询语句
多条件之中判断那个是否为空 如果为空填充1=1 不为空就为条件

 public static IDataReader ExecuteReader(DbCommand comm, string sql, params object[] value)
        {
            comm.CommandText = sql;
            if (value != null && value.Length >= 0)
            {
                if (comm.CommandText.IndexOf("?") == -1)
                {
                    string[] temp = sql.Split(‘@‘);
                    for (int i = 0; i < value.Length; i++)
                    {
                        string pName;
                        if (temp[i + 1].IndexOf(" ") > -1)
                        {
                            pName = "@" + temp[i + 1].Substring(0, temp[i + 1].IndexOf(" "));
                        }
                        else
                        {
                            pName = "@" + temp[i + 1];
                        }
                        //pName = "@p" + (i + 1).ToString();
                        DbParameter p = comm.CreateParameter();
                        p.DbType = DbType.String;
                        p.ParameterName = pName;
                        p.Value = value[i];
                        comm.Parameters.Add(p);
                    }
                }
                else
                {
                    string[] temp = sql.Split(‘?‘);
                    for (int i = 0; i < value.Length; i++)
                    {
                        temp[i] = temp[i] + "@p" + (i + 1).ToString();
                        string pName = "@p" + (i + 1).ToString();
                        DbParameter p = comm.CreateParameter();
                        p.DbType = DbType.String;
                        p.ParameterName = pName;
                        p.Value = value[i];
                        comm.Parameters.Add(p);
                    }
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < temp.Length; i++)
                    {
                        sb.Append(temp[i]);
                    }
                    comm.CommandText = sb.ToString();
                }
            }
            if (comm.Connection.State != ConnectionState.Open)
            {
                comm.Connection.Open();
            }
            return comm.ExecuteReader(CommandBehavior.CloseConnection);
        }

调用的时候类似:ExecuteReaderParams(comm, "select * from xx where id=? and name=?",id,name);
时间: 2024-08-01 07:37:26

C#参数化SQL查询的相关文章

如何编写高效的SQL查询语句

概述 如何编写性能比较高的SQL查询语句呢?两个方法:创建合理的索引:书写高效的SQL语句 索引的基本原理 索引分为聚集索引和非聚集索引.一个表只能创建一个聚集索引和N个非聚集索引,这句话的由来主要是由于索引的原理决定的. 数据库中的一张表不论你创建不创建索引,或者,不论你创建那种类型的索引,其在硬盘上的存储是一样的,那么,创建索引和不创建索引,或者,创建聚集索引和非聚集索引的区别在什么地方呢? 其区别是表内数据在内存的存在形式.对于没有创建索引的表,其加载到内存里时,就只有数据块:对于有聚集索

SQL Server中参数化SQL写法遇到parameter sniff ,导致不合理执行计划重用的一种解决方案

parameter sniff问题是重用其他参数生成的执行计划,导致当前参数采用该执行计划非最优化的现象.想必熟悉数据的同学都应该知道,产生parameter sniff最典型的问题就是使用了参数化的SQL(或者存储过程中使用了参数化)写法,如果存在数据分布不均匀的情况下,正常情况下生成的执行计划,在传入在分布数据较多的参数的情况下,重用了正常参数生成的执行计划,而这种缓存的执行计划并非适合当前参数的一种情况. 这种情况,在实际业务中,出现的频率还是比较高的,因为存储过程一般都是采用参数化的写法

参数化SQL

原文:http://www.cnblogs.com/aito/archive/2010/08/25/1808569.html 避免SQL注入的方法有两种:一是所有的SQL语句都存放在存储过程中,这样不但可以避免SQL注入,还能提高一些性能,并且存储过程可以由专门的数据库管理员(DBA)编写和集中管理,不过这种做法有时候针对相同的几个表有不同条件的查询,SQL语句可能不同,这样就会编写大量的存储过程,所以有人提出了第二种方案:参数化SQL语句.例如我们在本篇中创建的表UserInfo中查找所有女性

SQL Server SQL性能优化之--数据库在“简单”参数化模式下,自动参数化SQL带来的问题

数据库参数化的模式 数据库的参数化有两种方式,简单(simple)和强制(forced),默认的参数化默认是“简单”,简单模式下,如果每次发过来的SQL,除非完全一样,否则就重编译它(特殊情况会自动参数化,正是本文想说的重点)强制模式就是将adhoc SQL强制参数化,避免每次运行的时候因为参数值的不同而重编译,这里不详细说明. 这首先要感谢“潇湘隐者”大神的提示, 当时也是遇到一个实际问题, 发现执行计划对数据行的预估,怎么都不对,有观察到无论怎么改变参数,SQL语句执行前都没有重编译,疑惑了

Spring Data JPA原生SQL查询

package com.wanda.cms.dao.repository;import org.springframework.stereotype.Repository;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query;import java.math.BigInteger;import java.util.*; /*

oracle新建用户执行sql查询语句出现错误ORA-00942:表或视图不存在

oracle创建新用户后客户端执行SQL查询后出现错误提示如下: 执行查询语句如下: select * from sm_sales_order; ORA-00942:表或视图不存在 创建新用户并指定表空间和临时表空间 CREATE USER xxx IDENTIFIED BY xxxx DEFAULT TABLESPACE LMS TEMPORARY TABLESPACE TEMP; 授予系统权限connect grant connect to xxx; 授予对象权限,只限查询 grant se

提高SQL查询效率

1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null 可以在num上设置默认值0,确保表中num列没有null值,然后这样查询: select id from t where num=0 3.应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放

Hibernate 关于执行sql查询语句(转)

原文  http://www.yshjava.cn/post/543.html 主题 SQLHibernate Hibernate对原生SQL查询的支持和控制是通过SQLQuery接口实现的.通过Session接口,我们能够很方便的创建一个SQLQuery(SQLQuery是一个接口,在Hibernate4.2.2之前,默认返回的是SQLQuery的实现类--SQLQueryImpl对象,在下文中出现的SQLQuery如非注明,都是指该子类)对象来进行原生SQL查询: session.creat

笔记:Hibernate SQL 查询

Hibernate 支持使用原生的SQL查询,使用原生SQL查询可以利用某些数据库特性,原生SQL查询也支持将SQL语句放在配置文件中配置,从而提高程序的解耦,命名SQL查询还可以用于调用存储过程. SQL查询是通过SQLQuery接口来表示的,SQLQuery接口是Query接口的子接口,完全可以使用Query接口的方法,SQLQuery增加了二个重载方法 addEntity():将查询到的记录与特定的实体关联 addScalar():江查询的记录关联标量值 执行SQL的步骤如下: 获取Hib