gpt4 book ai didi

c# - 分配 SQL Server 数据库记录而不是静态数据

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:37 24 4
gpt4 key购买 nike

我在城市列表代码块中分配了静态数据,我在其中绑定(bind)了静态数据,例如:

country="Sri Lanka", 
city="Colombo",
latitude= Convert.ToDecimal(79.861243),
city_id= 4740,
longitude= Convert.ToDecimal(79.861243)

但我想从 SQL Server 数据库表中分配数据。有人可以指导我如何分配 country = sql_data_reader["country"].ToString(),SQL Server 数据行替换静态数据。

public void GetCities()
{
try
{
SqlConnection sql_con = new SqlConnection("Data Source=Mirzan;Initial Catalog=Numbeo_API;Integrated Security=True");
string sql_query = "SELECT * FROM Numbeo_API.dbo.cities";
sql_con.Open();

SqlCommand sql_command = new SqlCommand(sql_query, sql_con);
SqlDataReader sql_data_reader = sql_command.ExecuteReader();

List<City> city_list = new List<City>();

while (sql_data_reader.Read())
{
city_list.Add(new City
{
country = sql_data_reader["country"].ToString(),
city = sql_data_reader["city"].ToString(),
latitude = Convert.ToDecimal(sql_data_reader["latitude"]),
city_id = Convert.ToInt32(sql_data_reader["city_id"]),
longitude = Convert.ToDecimal(sql_data_reader["longitude"]),
});

foreach (var loop in city_list)
{
loop.country = sql_data_reader["country"].ToString();
loop.city = sql_data_reader["city"].ToString();
loop.latitude = Convert.ToDecimal(sql_data_reader["latitude"]);
loop.city_id = Convert.ToInt32(sql_data_reader["city_id"]);
loop.longitude = Convert.ToDecimal(sql_data_reader["longitude"]);
}
}
}
catch (Exception ex)
{
}
}

private List<City> cities = new List<City>()
{
new City() { country="Sri Lanka", city="Colombo", latitude= Convert.ToDecimal(79.861243), city_id= 4740, longitude= Convert.ToDecimal(79.861243)},
new City() { country="India", city="Mumbai", latitude= Convert.ToDecimal(19.075983), city_id= 4040, longitude= Convert.ToDecimal(72.877655)},
new City() { country="Sri Lanka", city="Galle", latitude= Convert.ToDecimal(6.230845), city_id= 4744, longitude= Convert.ToDecimal(80.187506)},
new City() { country="Sri Lanka", city="Matara", latitude= Convert.ToDecimal(5.949305), city_id= 4769, longitude= Convert.ToDecimal(80.535347)},
new City() { country="Sri Lanka", city="Kurunagala", latitude= Convert.ToDecimal(5.949305), city_id= 4769, longitude= Convert.ToDecimal(80.535347) },
};
}
}

最佳答案

请删除 foreach 循环,因为它不是必需的。

并在您想要显示数据的地方使用您的 list.property。

关于c# - 分配 SQL Server 数据库记录而不是静态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519654/

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