-2

I wrote this little function to do queries on a SQL Server 2005 database:

public DataSet Query(string query, Dictionary<string, string> parameters)
{
    DataSet result = new DataSet();

    using (SqlDataAdapter adapter = new SqlDataAdapter(query, sqlConnection))
    {
        adapter.SelectCommand.CommandType = CommandType.Text;
        adapter.SelectCommand.CommandText = query;
        foreach (KeyValuePair<string, string> pair in parameters)
        {
            adapter.SelectCommand.Parameters.Add(pair.Key, SqlDbType.Text).Value = pair.Value;
        }
        adapter.Fill(result);
    }

    return result;
}

When I call it like this:

Query("SELECT * FROM Database.Tab.le WHERE somecol LIKE '%1%'", new Dictionary<string, string>() {  });

I get a lot of results. But what I want is to call it like this:

Query("SELECT * FROM Database.Tab.le WHERE somecol LIKE '@number'", new Dictionary<string, string>() { {"@number", "%1%"}  });

This, however, returns zero rows. I would like to know why and how to fix it.

4

3 回答 3

6

试试下面

Query("SELECT * FROM Database.Tab.le WHERE somecol LIKE @number", new Dictionary<string, string>() { {"@number", "%1%"}  });

(在 sql as 中更改了 '@number'@number并给出参数 as @number

于 2013-08-12T08:18:19.440 回答
1

好的,您需要更改代码以使用 SqlParameter 对象。例如:

public DataSet Query(string query, Dictionary<string, string> parameters)
{
    DataSet result = new DataSet();

    using (SqlDataAdapter adapter = new SqlDataAdapter(query, sqlConnection))
    {
        adapter.SelectCommand.CommandType = CommandType.Text;
        adapter.SelectCommand.CommandText = query;
        foreach (KeyValuePair<string, string> pair in parameters)
        {
            //THIS BIT IS IMPORTANT, NOTE THE STRING FORMAT!
            adapter.SelectCommand.Parameters.Add(new SqlParameter(string.Format("@{0}", pair.Key), pair.Value));
        }
        adapter.Fill(result);
    }
    return result;
}
于 2013-08-12T08:21:32.573 回答
0

当您传递parameter给此查询时,您传递给它的数字可能not exists在数据库中。

并且在直接查询中%1%肯定会为您提供数据库中preceded or followed以 1 开头或具有的所有数字。(如果确实存在此类记录)

或尝试关注

Query("SELECT * FROM Database.Tab.le WHERE somecol LIKE @number", new Dictionary<string, string>() { {"@number", "%1%"}  });
于 2013-08-12T08:17:08.540 回答