以下代码:
public IEnumerable<AccountStructModel> Query(string query)
{
List<AccountStructModel> output = new List<AccountStructModel>();
using (SqlConnection connection = new SqlConnection("MyConnectionString"))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.CommandText = query;
command.CommandType = CommandType.Text;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for (int x = 0; x < reader.FieldCount; x++)
{
output.Add(new AccountStructModel { Username = reader[1].ToString(), Password = reader[2].ToString() });
}
}
command.Dispose();
}
connection.Close();
connection.Dispose();
}
return output;
}
提供以下输出:
Username | Password
---------|---------
Tim | randomPassword
问题从这里开始:
new AccountStructModel { Username = reader[1].ToString(), Password = reader[2].ToString() }
我似乎无法找到实现循环的方法来处理以下问题:reader[i]
而不是reader[1]
,reader[2]
,{{ 1}},reader[3]
,也许答案很明显,但我似乎无法轻易找到答案。