C# AddWithValue不适用于SqlCommand查询

C# AddWithValue不适用于SqlCommand查询,c#,asp.net,sql-server,C#,Asp.net,Sql Server,只要我使用有效的列名,下面代码中的方法GetData就可以工作,但是,当尝试在SQL查询中使用变量(查询字符串参数值)时,我会得到空结果 我假设我没有正确使用.AddWithValue方法。我是否没有正确编写SQL命令,或者它与.AddWithValue方法调用的代码位置有关?还是我错过了什么 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.

只要我使用有效的列名,下面代码中的方法
GetData
就可以工作,但是,当尝试在SQL查询中使用变量(查询字符串参数值)时,我会得到空结果

我假设我没有正确使用
.AddWithValue
方法。我是否没有正确编写SQL命令,或者它与
.AddWithValue
方法调用的代码位置有关?还是我错过了什么

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.FriendlyUrls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace Koobek
{
    public partial class WebForm6 : System.Web.UI.Page
    {
        string cat = "";
        string getcat = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            var segments = Request.GetFriendlyUrlSegments();
            int count = segments.Count;

            if (segments.Count > 0)
                cat = segments[0];

            string getcat = Request.QueryString["cat"];

            ListView1.DataSource = this.GetData();
            ListView1.DataBind();

            System.Diagnostics.Debug.WriteLine(getcat);
        }

        private DataSet GetData()
        {  
            string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            string query = @"SELECT DISTINCT newcatdisplay, newclassdisplay, newclass, newcat FROM ejn_series WHERE newcat = @getcat ORDER BY newclassdisplay";
            SqlCommand cmd = new SqlCommand(query);
            cmd.Parameters.AddWithValue("@getcat", getcat);

            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;

                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);

                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            System.Console.WriteLine("empty");
                        }

                        return ds;
                    }
                }
            }
        }        
    }
}

不能向文本sql语句添加参数。这样做:

 string query = @"SELECT DISTINCT newcatdisplay, newclassdisplay, 
        newclass, newcat FROM ejn_series WHERE newcat = '" +  getcat + "' " +
        "ORDER BY newclassdisplay";

我认为问题在于使用
定义
数据集的方式。只要
返回
数据集
,它就会使用
块退出
,并处理它。尝试使用
删除
,并使其成为一个普通变量声明。不过,如果我用newclass(有效的表名)替换查询字符串中的@cat,我会得到结果,您应该尝试使用调试器并检查变量cat是否真的具有您期望的值
cat
的值是什么?您是指有效的列名,而不是表名,对吗?表名
ejn_series
已经在查询中硬编码。就我个人而言,我不会以这种方式执行sql文本,而是使用存储过程