2017-01-06 253 views
2

我似乎无法得到这个工作:SQL查询返回列表

我的表列标题是“流派”“艺术家”“专辑” ,我传递的(类型,过滤器的参数,可以价值)(“艺术家”,“风格”,“摇滚”),其中有两行的数据库与“摇滚”的流派。

当我按照调试器,写入到列表中的“而(reader.Read())”必须返回false,因为从来没有进入环,因此没有什么。

public static List<String> getWithFilter(String type, String filter, String value) 
    { 

     List<String> columnData = new List<String>(); 

     string query = "SELECT @type FROM Music WHERE" + 
      " @filter = '@value'"; 
     SqlConnection connection = Database.GetConnection(); 
     SqlCommand getData = new SqlCommand(query, connection); 
     getData.Parameters.AddWithValue("@type", type); 
     getData.Parameters.AddWithValue("@filter", filter); 
     getData.Parameters.AddWithValue("@value", value); 
     connection.Open(); 

     using (connection) 
     { 
      using (getData) 
      { 
       using (SqlDataReader reader = getData.ExecuteReader()) 
       { 
        while (reader.Read()) 
        { 
         columnData.Add(reader.GetString(0)); 
        } 
       } 
      } 
     } 
     return columnData; 
    } 
+0

您的查询是有点乱的 - 你不能使用参数,你使用它们的方式。你能解释你想要查询的内容吗?还请显示您的表格结构,您传递的参数以及所需的输出。 – Siyual

+1

您不能使用参数列名称的名称,并且在使用它们时不要将引号放在它们周围。您必须实际构建查询,比如'“SELECT”+ type +“FROM ... WHERE”+ filter +“= @value”;' – juharr

+1

使用SQL参数很好,但'type'和'filter '不能是参数,因为它们表示列名,据我所知。 –

回答

1

您不能使用参数列的名称,并且在使用它们时不要在引号周围加引号。现在您的查询相当于

SELECT 'artist' FROM Music WHERE 'genre' = '@value' 

您可以改为执行下列操作。

string query = "SELECT " + type + " FROM Music WHERE " + filter + " = @value"; 

而只是删除创建@type@fitler参数线。

+0

完美,谢谢。 –

+0

我就不会这样容易受到SQL注入攻击? – maccettura

+0

@maccettura只有'type'和或'filter'是用户输入。如果他们是那么OP应该先检查它们对有效的列名的列表。 – juharr

0

你要找无论是格式化串插(需要C#6.0):

string query = 
    [email protected]"SELECT {type} 
     FROM Music 
     WHERE {filter} = @value"; 

... 

getData.Parameters.AddWithValue("@value", value); 

格式是有点多罗嗦:

string query = String.Format(
    @"SELECT {0} 
     FROM Music 
     WHERE {1} = @value", type, filter); 
0

我假设你”重新使用.net 2

DateTime current = DateTime.Now; 
     Console.WriteLine(current); 
     SqlConnection conn = new SqlConnection(); 
     string q = "SELECT @field FROM student"; 
     SqlDataAdapter da = new SqlDataAdapter(q, conn); 
     da.SelectCommand.Parameters.AddWithValue("@field", "snName"); 
     DataTable dt = new System.Data.DataTable(); 
     conn.Open(); 
     da.Fill(dt); 
     conn.Close(); 
     List<string> names = new List<string>(); 
     foreach (DataRow dr in dt.Rows) 
     { 
      names.Add(dr[0].ToString()); 
     } 
     Console.WriteLine("Fetching {0} data for {1}", names.Count, DateTime.Now - current); 
     Console.ReadKey(); 

您可以使用lambda表达式来映射在.NET中的数据表> 4