如何使用ASP.NET C#进行异化查询 [英] How to do paramitrized query using ASP.NET C#

查看:76
本文介绍了如何使用ASP.NET C#进行异化查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友们,



我正在尝试创建一个低估的查询,来比较价格。

这是我使用的查询,问题是它没有向我显示任何东西,或者有时它显示'必须声明标量变量'@ prc1。 。



(请在修改我的代码后发布您的答案以便更好地理解)。





检查是我的查询对吗?

检查也是我的寄生代码对吗?



我有什么试过:



Hi friends,

I am trying to create the paramitrized query , to compare price.
This is the query that i use , the problem is that it does not show me to anything or sometime it show 'Must declare the scalar variable "@prc1". .

(please please post your answers with modifying my code for better understanding).


Check is my query right ?
Check also is my paramitrized code right ?

What I have tried:

public partial class Searchpage : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();
    //string price1;
   // string price2;
    //string osx;
    //string checktwog;
    //string checkthreeg;
    //string checkfourg;
    //string phonetype;
    //string cam;
    //string ram;
    //string q;
    protected void Page_Load(object sender, EventArgs e)
    {
        con.ConnectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        con.Open();
        try
        {
         
            string price1 = Convert.ToString(Session[price1]);

          String q = SELECT * FROM legacy WHERE [price] >= @prc1";
          
              SqlCommand comm = new SqlCommand(q, con);
           comm.Parameters.AddWithValue(@prc1, price1);
           SqlDataSource1.SelectCommand = q;
           SqlDataSource1.DataBind();
           
        }
        catch (Exception ex)
        {
            
            Response.Write(ex.ToString());
        }
        
    }

推荐答案

首先不使用字符串,并使用更合适的数据类型:在这种情况下 int double decimal ,具体取决于数据库中的Price列。转换字符串(必要时使用TryParse)和strore它在Session中作为合适的类型。

假设所有价格都是整数。

Start by not using strings all the time, and use more suitable datatypes: in this case int, double, or decimal depending on the Price column in your database. Convert the string (using TryParse if necessary) and strore it in the Session as the appropriate type.
Let's assume all prices are integers.
int price = (int) Session["Price"];
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Legacy WHERE Price >= @PRC", con))
        {
        cmd.Parameters.AddWithValue("@PRC", price);
        SqlDataSource1.SelectCommand = cmd;
        SqlDataSource1.DataBind();
        }
    }


comm.Parameters.AddWithValue(@ prc1,price1);
comm.Parameters.AddWithValue("@prc1", price1);


这篇关于如何使用ASP.NET C#进行异化查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆