-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

OK、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%、DB内のすべての数字が1で始まるか、1で始まることが確実になりますpreceded or followed.(そのようなレコードが存在する場合)

またはフォローしてみてください

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