首页 > 解决方案 > c# - 从具有多条记录的数据库中返回的 SELECT 语句

问题描述

我正在用 asp.net 做一个小项目。部分任务是我从 SQL Server 数据库中检索信息。到目前为止,我只需要单个记录,所以我使用了以下代码:

public string getTwitterSearchHistory(string userId)
{
    if (userId != null)
    {
        List<string> history = new List<string>();
        string result = "";
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        conn.Open();

        SqlCommand command = new SqlCommand("SELECT searchedTerm FROM dbo.TwitterSearchHistoryModels WHERE userId = @userId", conn);
        command.Parameters.AddWithValue("@userId", userId);
        using (SqlDataReader reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                result = String.Format("{0}", reader["searchedTerm"]);
            }
        }

        conn.Close();
        return result;
    }
    return "";
}

现在,当我想从一条记录中检索属性时,此代码可以完美运行。但是,现在我需要从多个属性中检索一个属性。意思是,假设我有以下内容:

ID | UserId | searchedTerm
--------------------------------
1  | 1      | hello
2  | 1      | anothersearchedterm
3  | 1      | this is a term

如何检索 userId 1 的所有 searchedTerms 并将它们存储在某种数组中?

谢谢!

**编辑:我正在向我的控制器内部的方法发送 Ajax 请求。

function loadHistory() {
    var detailsForGet = {
        userId: sessionStorage.getItem("userName")
    }
    $.ajax({
        type: "GET",
        url: "https://localhost:44326/User/getTwitterSearchHistory",
        data: detailsForGet,
        success: function (data) {
            console.log(data)
        }
    });
}

现在,在控制器中,我有这个从本地数据库执行选择查询的方法:

public List<string> getTwitterSearchHistory(string userId)
{
    if (userId != null)
    {
        List<string> history = new List<string>();
        string result = "";
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        conn.Open();
        SqlCommand command = new SqlCommand("SELECT searchedTerm FROM dbo.TwitterSearchHistoryModels WHERE userId = @userId", conn);
        command.Parameters.AddWithValue("@userId", userId);
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                history.Add(String.Format("{0}", reader["searchedTerm"]));
            }
        }

        conn.Close();
        return history;
    }
    return null;
}

现在,在调试时,我可以看到变量 history 保持良好的值,但是,在我成功调用 w ajax 时,当我尝试打印数据时,我得到以下信息:System.Collections.Generic.List`1[ System.String].. 请问我做错了什么?谢谢

标签: c#sqlasp.net

解决方案


推荐阅读