【发布时间】:2017-05-21 15:42:00
【问题描述】:
我似乎无法正常工作:
我的表格列标题是“流派”“艺术家”“专辑” 我传入的参数是(类型,过滤器,值)(“艺术家”,“流派”,“摇滚”),其中数据库中有两行,流派为“摇滚”。
当我跟随调试器时,'while (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;
}
【问题讨论】:
-
列名不能使用参数,使用时也不能用引号引起来。您必须实际构建查询,例如
"SELECT " + type + " FROM... WHERE " + filter + " = @value"; -
使用SQL参数很好,但
type和filter不能是参数,因为它们代表我理解的列名。 -
你确定吗?如果可以以这种方式使用参数(我不确定),则选择看起来像
select 'artist' from music where 'genre' = ''Rock''。 -
@CraigHalloway 不,你写它的方式执行的查询是
SELECT 'artist' FROM Music WHERE 'genre' = 'Rock'。请注意 "artist` 和 "genre" 周围的单引号,这会将它们转换为字符串文字。当然,WHERE条件永远不会满足。 -
@IvanStoev 实际上我相信是
'genre' = '@value',因为它们在最后一个参数周围有多余的引号。
标签: c# mysql sql winforms visual-studio