【发布时间】:2022-01-16 14:20:59
【问题描述】:
public static Article GetJournalById(string ConnectionString,int Id)
{
using(SqlConnection sql = new SqlConnection(ConnectionString))
{
using(SqlCommand cmd = new SqlCommand("GetJournalById", sql))
{
Article article = new Article();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Id", Id);
sql.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
article.Id = Id;
article.Title = reader.GetString(1).ToString();
article.Summary = reader.IsDBNull(2) ? string.Empty : reader.GetString(2).ToString();
article.Tag = reader.GetString(3).ToString();
article.Author = reader.GetString(4).ToString();
article.Ban = reader.GetByte(5);
article.BanReason = reader.IsDBNull(6) ? string.Empty : reader.GetString(6).ToString();
article.Date = reader.GetDateTime(7);
}
}
return article;
}
}
}
如何获取多行? 我知道如果需要单行多列,我可以像上面那样做。 但是如何获得多行? 我想获取多行并从函数中返回它们。 我还想在视图页面上显示返回值。 但我不知道怎么做,也不知道要搜索什么搜索词。 请帮帮我。
这是文章模型。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace News.Models
{
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string Tag { get; set; }
public string Author { get; set; }
public byte Ban { get; set; }
public string BanReason { get; set; }
public DateTime Date { get; set; }
}
}
以下是从存储过程中获取多个帖子的代码。 (不完整,未解决)
public static int GetJournalByDate(string ConnectionString,DateTime date)//must be fix
{
using (SqlConnection sql = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("GetJournalByDate", sql))
{
try
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("@Date", System.Data.SqlDbType.DateTime2, 7).Value = date;
sql.Open();
cmd.ExecuteReader();
return 1;
}
catch
{
return 0;
}
}
}
}
【问题讨论】:
-
您的
while循环只需要在每次迭代中创建一个新的Article并将其添加到某种列表中。还有一个拉多行的查询。 -
@DaleK 我应该用 what..kind 编辑它吗?
-
@DaleK 只是用文章创建一个列表?
-
我注意到您没有接受任何问题的答案 - 这是有原因的吗?
标签: c# asp.net sql-server asp.net-mvc