SqlDataAdapter:空结果

时间:2013-08-12 08:12:45

标签: c# sql sql-server sql-server-2005

我写了这个小函数来对SQL Server 2005数据库进行查询:

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;
}

当我这样称呼时:

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

我得到了很多结果。但我想要的是这样称呼它:

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

然而,这会返回零行。我想知道为什么以及如何解决它。

3 个答案:

答案 0 :(得分:6)

尝试以下

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

(已更改&#39; @ number&#39;在sql中为@number,并将参数设为@number

答案 1 :(得分: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;
}

答案 2 :(得分: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%"}  });