sql多表查询,将结果集合到list集合中,并在ashx输出为json字符串
已使用过的方法:
1.
实体类:
都2023年了,为啥不用 Linq To Entity
直接就是对象
如果配合用 ASP.NET MVC
直接 return JsonResult(对象)
完美搞定
首先,需要在SQL中编写多表查询语句,并使用JOIN语句将多个表连接起来,例如:
SELECT t1.id, t1.name, t2.address, t3.phone
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
JOIN table3 t3 ON t1.id = t3.id
然后,在C#中定义一个包含需要查询结果字段的类:
public class QueryResult {
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
接下来,使用ADO.NET连接到数据库,并执行SQL查询语句,将查询结果转换为List<QueryResult>泛型集合:
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<QueryResult> results = new List<QueryResult>();
while (reader.Read()) {
QueryResult result = new QueryResult();
result.Id = (int)reader["id"];
result.Name = (string)reader["name"];
result.Address = (string)reader["address"];
result.Phone = (string)reader["phone"];
results.Add(result);
}
reader.Close();
}
最后,在ASHX处理程序中将List<QueryResult>转换为JSON字符串并输出:
context.Response.ContentType = "application/json";
context.Response.Write(JsonConvert.SerializeObject(results));