AddWithValue不能处理SqlCommand查询

时间:2017-07-11 19:51:44

标签: 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.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;
                    }
                }
            }
        }        
    }
}

1 个答案:

答案 0 :(得分:0)

您无法将参数添加到文本sql语句中。这样做:

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