string connectionString = ConfigurationManager.AppSettings["AllRttpDBConnectionString"];
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "Select * from test where ServiceName like 'T%' " ;
try
{
connection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
MySqlDataReader reader;
reader = command.ExecuteReader();
while (reader.Read())
{
Player.Name = reader["Name"].ToString();
Player.Number = Convert.ToInt32(reader["Number"].ToString());
//push to list
PlayerList.Add(Player);
}
connection.Close();
}
catch (Exception e)
{
connection.Close();
logger.Info(e.ToString());
}
上面是我用来从数据库中读取多行到列表的代码。但是,我的所有列表项都具有完全相同的数据(数据库的最后一行)。
我知道这可能是一个非常简单,愚蠢的错误,但我只是看不到它。
答案 0 :(得分:6)
看起来您反复添加相同的对象,将值更改为从当前行读取的值。你需要使用:
Player player = new Player()
player.Name = reader["Name"].ToString();
player.Number = Convert.ToInt32(reader["Number"].ToString());
//push to list
PlayerList.Add(player);
然后将其添加到集合中。
答案 1 :(得分:4)
看起来您正在不断修改单个Player
实例。
要修复它,请为每条记录创建一个新实例:
while (reader.Read())
{
// I'm guessing about the type here
Player player = new Player();
player.Name = reader["Name"].ToString();
player.Number = Convert.ToInt32(reader["Number"].ToString());
//push to list
PlayerList.Add(player);
}
答案 2 :(得分:2)
所以发生的事情是,每次将其添加到列表中时,您都不会创建新的Player
。
将项目添加到列表时,您的代码应如下所示。
PlayerClass NewPlayer = new PlayerClass;
NewPlayer.Name = reader["Name"].ToString();
NewPlayer.Number = Convert.ToInt32(reader["Number"].ToString());
//push to list
PlayerList.Add(NewPlayer);
答案 3 :(得分:2)
我建议您稍微改进一下代码:
public IEnumerable<Player> GetPlayers()
{
string connectionString = ConfigurationManager.AppSettings["AllRttpDBConnectionString"];
using (var conn = new MySqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name, Number FROM test WHERE ServiceName LIKE 'T%';";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Player
{
Name = reader.GetString(0),
Number = reader.GetInt32(1)
};
}
}
}
}
当你需要创建一个列表时:
List<Player> playersList = GetPlayers().ToList();
您还需要确保妥善处理所有可支配资源,如我的示例所示。