关于ADO.NET参数化查询的提问

最近我们的正式环境一直在报错一个异常,首先我贴出来异常信息

BLL层 捕获到了请求的url

Net.BLL.MobileFun MobileFun.GetBusinessBidPolicy 异常

传入参数为:AucId=643129;CarId=680362;businessid:41773;

异常信息为:必须声明标量变量 "@UID"。 必须声明标量变量 "@UID"。 必须声明标量变量 "@UID"。

URL:http://*********.com/httpHandler/ForMobileServiceHandler.ashx?action=getBidPolicy&aucId=643129&carId=680362&businessid=BC440DE0D6DCA7FD&version=v3.2.8&onlineid=021d162e-ba3e-45ac-8c59-8d265522d6ef&clienttype=0

Dao层捕获到的异常信息

Net.DAL.AuctionDao 位置:Net.DAL.AuctionDao,方法:GetBidPolicy,错误信息:System.Data.SqlClient.SqlException (0x80131904): 必须声明标量变量 "@UID"。 必须声明标量变量 "@UID"。 必须声明标量变量 "@UID"。 在 System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) 在 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) 在 System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() 在 System.Data.SqlClient.SqlDataReader.get_MetaData() 在 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) 在 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) 在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) 在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) 在 System.Data.SqlClient.SqlCommand.ExecuteScalar() 在 Net.DBUtility.MySqlHelper.ExecuteScalar(SqlConnection connection, CommandType commandType, String commandText, SqlParameter[] commandParameters) 在 Net.DBUtility.MySqlHelper.ExecuteScalar(String connectionString, CommandType commandType, String commandText, SqlParameter[] commandParameters) 在 Net.DBUtility.MySqlDataProvider.GetSingle(String SQLString, IDataParameter[] cmdParms) 在 Net.DAL.AuctionDao.GetBidPolicy(String aucId) ClientConnectionId:48c2084f-c6b0-46b5-93b9-8a59ebcd29ed

现在我贴出来 我这几个方法

BLL层

        public string GetBusinessBidPolicy(string AucId, string CarId, string businessid)
        {
            ConvertToJson ctj = new ConvertToJson();
            try
            {
                int tag = -1;
                int Offer = 0;
                int price = 0;
                int priceNonlocal = 0;
                objAuctionDao.GetBusinessBidInfo(AucId, CarId, ref tag, ref Offer, ref  price, ref  priceNonlocal, businessid);
                ctj.Append("ResId", "0");
                ctj.Append("ResMsg", "获取商户出价方案和报价成功!");
                ctj.Append("BidWay", tag);//0:本市;1 外迁;-1 尚未选择出价方式
                ctj.Append("price", price);
                ctj.Append("priceNonlocal", priceNonlocal);
                ctj.Append("MyOptimizationOffer", Offer);
            }
            catch (Exception e)
            {
                ctj.Append("ResId", "1");
                ctj.Append("ResMsg", "出现异常,获取商户出价方案和报价失败!");
                m_objLog.Error("MobileFun.GetBusinessBidPolicy 异常    传入参数为:AucId=" + AucId + ";CarId=" + CarId + ";businessid:" + businessid + ";异常信息为:" + e.Message+"URL:"+HttpContext.Current.Request.Url);
            }
            return ctj.ToObject();
        }

DAO层

   public void GetBusinessBidInfo(string aucId, string CarId, ref int tag, ref int Offer, ref int price, ref int priceNonlocal, string businessID = "")
        {

            try
            {
                string busID = "";
                if (string.IsNullOrEmpty(businessID))
                    busID = new MemberDto().BusinessId;
                else
                    busID = businessID;
                //-1 需要出价承诺,其他不需要车价承诺
                int tag1 = GetBidPolicy(aucId);
                if (tag1 != 1 && tag1 != 2 && tag1 != 4 && tag1 != 3)
                {
                    tag = 0; return;
                }

                //            _strSql = string.Format(@"SELECT TOP 1 Tag FROM tbAuction_BidPolicyNow with(nolock) WHERE AucId = {0} AND BusinessId = {1} ORDER BY Created DESC
                //                                    SELECT Offer FROM tbSHD_OptimizationQuote with(nolock)  WHERE BusinessID={1} AND AucID={0}
                //                                    SELECT TOP 1 ISNULL(price,0) price,ISNULL(priceNonlocal,0) priceNonlocal FROM tbAuction_Evaluate with(nolock)  WHERE businessId={1} AND carid={2}  ORDER BY created desc
                //                                    ", aucId, busID, CarId);
                _strSql =
                        @"SELECT TOP 1 Tag FROM tbAuction_BidPolicyNow with(nolock) WHERE AucId = @AucID AND BusinessId = @UID ORDER BY Created DESC
                                    SELECT Offer FROM tbSHD_OptimizationQuote with(nolock)  WHERE [email protected] AND [email protected]
                                    SELECT TOP 1 ISNULL(price,0) price,ISNULL(priceNonlocal,0) priceNonlocal FROM tbAuction_Evaluate with(nolock)  WHERE [email protected]  AND [email protected]  ORDER BY created desc
                                    ";
                SqlParameter[] par = { new SqlParameter("@AucID", aucId), new SqlParameter("@UID", businessID), new SqlParameter("@CarID", CarId) };
                DataSet obj = _loacaldbRead.Query(_strSql, par);
                if (obj != null && obj.Tables.Count > 0)
                {
                    if (obj.Tables[0].Rows.Count > 0)
                    {
                        tag = int.Parse(obj.Tables[0].Rows[0][0].ToString());
                    }
                    else
                    {
                        tag = -1;
                    }
                    if (obj.Tables[1].Rows.Count > 0)
                    {
                        Offer = int.Parse(obj.Tables[1].Rows[0][0].ToString());
                    }
                    if (obj.Tables[2].Rows.Count > 0)
                    {
                        price = int.Parse(obj.Tables[2].Rows[0][0].ToString());
                        priceNonlocal = int.Parse(obj.Tables[2].Rows[0][1].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                string error = string.Format("位置:{0},方法:{1},错误信息:{2}", this.GetType().ToString(),
                    System.Reflection.MethodBase.GetCurrentMethod().Name, e);
                _log.Error(error);
                throw;

            }
       public int GetBidPolicy(string aucId)
        {
        //    _strSql = string.Format("SELECT nonlocaltag FROM tbauction_baseinfo with(nolock) WHERE id = {0}", aucId);

            try
            {
                _strSql = "SELECT nonlocaltag FROM tbauction_baseinfo with(nolock) WHERE id = @AucID";
                SqlParameter[] par = { new SqlParameter("@AucID", aucId) };
                object obj = _loacaldbRead.GetSingle(_strSql, par);
                if (obj == null) return -1;
                return Convert.ToInt32(obj);
            }
            catch (Exception e)
            {
                string error = string.Format("位置:{0},方法:{1},错误信息:{2}", this.GetType().ToString(),
                    System.Reflection.MethodBase.GetCurrentMethod().Name, e);
                _log.Error(error);
                throw;

            }

        }

我一直很奇怪 我用写的参数化查询语句  然后值初始化在参数数组中丢给ADO.NET执行,为什么会说我没有声明@UID这个变量呢?

而且还有一个异常 无法找到表1

GetBidPolicy  这个方法中根本没有用到@UID的参数但是报错却说Net.DAL.AuctionDao 位置:Net.DAL.AuctionDao,方法:GetBidPolicy,错误信息:System.Data.SqlClient.SqlException (0x80131904): 必须声明标量变量 "@UID"。 必须声明标量变量 "@UID"。 必须声明标量变量 "@UID"。

现在可以确定 找不到表1 的这个异常是

if (obj.Tables[1].Rows.Count > 0)
                    {
                        Offer = int.Parse(obj.Tables[1].Rows[0][0].ToString());
                    }

这里取 table[1].rows.count  的时候 发现dataset中 表1 null  所以抛出这个异常

那么问题来了 我的三个查询一起执行 就算没有查询到数据  dataset 中也会有三张表 即便是空表 也不能没有表

现在请教  各位 这个异常到底是什么原因产生的呢?

URL 我本地,生产环境都试过了 直接敲出来没有报错异常..

另请教 参数化的sql语句  ado.net 去数据库执行的时候 是如何把值赋给参数的 ,求详解!

时间: 2024-08-11 23:31:13

关于ADO.NET参数化查询的提问的相关文章

ADO.NET 参数化查询

使用参数化查询的情景有很多,但最常用的情景是需要用户在查询中进行输入的情况. 有两种方法可供使用.第一,可以讲用户输入嵌入到查询字符串中,例如可能使用.NET Framework中的String.Format函数. 第二种方法是构造一种参数化查询.      在开始时执行如下所示的基本查询: 1 select count(*) from UserInfo 2 3 4 where UserName=‘{0}’ and PassWord=‘{1}’      然后利用用户的输入构造如下查询: 1 s

参数化查询

参数化查询(Parameterized Query 或 Parameterized Statement)是指在设计与数据库链接并访问数据时,在需要填入数值或数据的地方,使用参数 (Parameter) 来给值,这个方法目前已被视为最有效可预防SQL注入攻击 (SQL Injection) 的攻击手法的防御方式. 原理: 在使用参数化查询的情况下,数据库服务器不会将参数的内容视为SQL指令的一部份来处理,而是在数据库完成 SQL 指令的编译后,才套用参数运行,因此就算参数中含有恶意的指令,由于已经

SQL参数化查询

参数化查询(Parameterized Query 或 Parameterized Statement)是指在设计与数据库链接并访问数据时,在需要填入数值或数据的地方,使用参数 (Parameter) 来给值,这个方法目前已被视为最有效可预防SQL注入攻击 (SQL Injection) 的攻击手法的防御方式. 原理 在使用参数化查询的情况下,数据库服务器不会将参数的内容视为SQL指令的一部份来处理,而是在数据库完成 SQL 指令的编译后,才套用参数运行,因此就算参数中含有恶意的指令,由于已经编

参数化查询比拼接字符串慢的原因

我们都知道,参数化查询可以处理SQL注入,以及提高查询的效率,因为参数化查询会使MSSQL缓存查询的计划. 但是现在我发现一个奇怪的问题,就是参数化查询比字符串拼接要慢,而且速度相差10倍之多. SQL语句是: select * from T_Message where T_Message.BelongTo=@BelongTo 开始在ADO.NET中用SqlParameter传递参数@BelongTo时是这么写的 SqlParameter param1 = new SqlParameter("@

为什么参数化查询可以防止SQL注入?(转)

昨天被某大牛问了一个问题,为什么SQL参数化查询可以防止SQL注入,参数化查询的原理是什么? 结果闷逼了,之前只知道参数化查询是可以防止SQL注入,但是没有深究其原理,今天就找一些文章,学习一下,也分享给大家. 以下引用知乎大神们的回答: 原理是采用了预编译的方法,先将SQL语句中可被客户端控制的参数集进行编译,生成对应的临时变量集,再使用对应的设置方法,为临时变量集里面的元素进行赋值,赋值函数setString(),会对传入的参数进行强制类型检查和安全检查,所以就避免了SQL注入的产生. 最近

Sql Server参数化查询之where in和like实现详解

来自:http://www.cnblogs.com/lzrabbit/archive/2012/04/22/2465313.html#wherein 文章导读 拼SQL实现where in查询 使用CHARINDEX或like实现where in 参数化 使用exec动态执行SQl实现where in 参数化 为每一个参数生成一个参数实现where in 参数化 使用临时表实现where in 参数化 like参数化查询 xml和DataTable传参  身为一名小小的程序猿,在日常开发中不可以

使用dapper进行参数化查询

在使用Dapper操作Mysql数据库中我介绍了使用dapper进行CURD基本操作,但在示例代码中参数虽然也是通过@开头,但其实不是真正意义的参数化查询,而是拼接sql,这种方式不利于防止sql注入,所以在Dappe中可以使用DynamicParameters动态参数集合添加参数,从而实现dapper下的参数化查询: 示例代码 using (var connection = new MySqlConnection(connstr)) { //声明动态参数 DynamicParameters P

.NET 出现参数化查询 需要参数但未提供该参数的错误

1.问题的来源 在.NET或者C#中,我们一般执行sql语句的话,推荐使用参数化查询,这样可以避免sql注入的攻击,但是,我在使用参数化查询的时候 出现了以下的错误,详细如下图: 图一这是写sql语句参数化查询的代码 图2 这是MSSQL执行的sql语句 2.问题的原因   出现这种错误的原因在于,在参数化查询的时候,有几个参数的值为null,这样的话,就出现了如图2所示的错误. 为啥会这样了?? 虽然参数的值就是为null,传入数据库中就必须变成DbNull.Value因为此null为c#的,

参数化查询为什么能够防止SQL注入

很多人都知道SQL注入,也知道SQL参数化查询可以防止SQL注入,可为什么能防止注入却并不是很多人都知道的. 本文主要讲述的是这个问题,也许你在部分文章中看到过这块内容,当然了看看也无妨. 首先:我们要了解SQL收到一个指令后所做的事情: 具体细节可以查看文章:Sql Server 编译.重编译与执行计划重用原理 在这里,我简单的表示为: 收到指令 -> 编译SQL生成执行计划 ->选择执行计划 ->执行执行计划. 具体可能有点不一样,但大致的步骤如上所示. 接着我们来分析为什么拼接SQ