c# - 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].. 请问我做错了什么?谢谢
解决方案
推荐阅读
- java - OBJECT EQUALS 方法在内部做什么?如何知道存储在对象中的值,例如:Object_Comparison?
- javascript - 反应还原onChange 更新值问题
- azure-maps - Azure-Maps Get Search Address Structured API 没有为“美国密歇根州”提供正确的结果
- c# - 如何显示学生的主题列表而不是学生主题的链接类?
- gradle - 项目依赖项中的排除不会反映在 Gradle 中的其他依赖项中
- mysql - 在 MySql 文档主页中定义删除
- javascript - 传递道具 Child -> Parent -> Other Child
- python - 如何在python中拆分具有多个条件的字符串?
- javascript - div元素在CSS之后不显示
- python-3.7 - Python 3.7 关于PEP 484 多类型怎么解释呢?