gpt4 book ai didi

c# - 如何在 C# 中从 SQL 设置数据动态数组

转载 作者:行者123 更新时间:2023-11-30 15:52:43 25 4
gpt4 key购买 nike

如何在 C# 中从 SQL Server 设置数据。

我类学生:

public class student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

我想从 SQL 设置数据

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * From Student";
cmd.Connection = con;
DataTable datatable = new DataTable();
con.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
sqlDataAdapter.Fill(datatable);
con.Close();
sqlDataAdapter.Dispose();
foreach (DataRow dr in datatable.Rows)
{
//Set Data: ex: student[] students=new student[];
//students=new students{StudentID=dr["ID"],FirstName=dr["FirstName"]}
// ...
}

和我的代码集数据

namespace WebApi2.myapi
{
public class StudentController : ApiController
{
student[] students = new student[]
{
new student { StudentID = 1, FirstName = "Jishan", LastName = "Siddique" },
new student { StudentID = 2, FirstName = "Bharat", LastName = "Darji" },
new student { StudentID = 3, FirstName = "Ravi", LastName = "Mori" },
new student { StudentID = 4, FirstName = "Jay", LastName = "Singh" }
};

public IEnumerable<student> GetStudents()
{
return students;
}
}
}

Finally: I would like 1 result like: student.StudentID = dr ["ID"]; student.FirstName = dr ["FirstName"]

谢谢大家观看。抱歉我的英语不好。

我在 google 上搜索到结果但没有找到

最佳答案

您可以通过从 DataRow 获取值来实现:

List<student> students = new List<student>();
foreach (DataRow dataRow in datatable.Rows)
{

students.Add(new student(){
StudentID =dataRow["StudentID"];
FirstName = dataRow["FirstName"] ;
LastName = dataRow["LastName"] ;
})
}

因此,students 集合将包含所有学生。

关于c# - 如何在 C# 中从 SQL 设置数据动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53720468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com