2017-07-11 4 views
-1

次のコードのメソッドGetDataは有効な列名を使用している限り動作しますが、SQLクエリで変数(クエリ文字列パラメータ値)を使用すると空の結果が得られます。AddWithValueがSqlCommandクエリで機能しない

私は.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; 
        } 
       } 
      } 
     }   
    } 
} 
+3

「データセット」を「使用する」ように定義する方法に問題があると思います。 'DataSet'を'返す 'とすぐに 'using'ブロックを終了し、それを破棄します。 'using'を取り除き、それを通常の変数宣言にしてみてください。 –

+0

また、クエリ文字列の@catをnewclass(有効なテーブル名)に置き換えると結果が得られます。 – codeRed

+0

さて、デバッガを使って実際に変数_cat_に期待する値があるのを確認してください。 – Steve

答えて

0

テキストSQL文にパラメータを追加することはできません。これを行う:

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

個人的には、このようにSQL文を実行することはありませんが、代わりにストアドプロシージャ – Gregg

関連する問題