ksa*_*der 3 c# sql sql-server asp.net
我有一个包含6列和5行的表.我想选择所有行并使用SqlDataReader(ASP.NET C#)读取它们.我目前可以使用dataReader["columnName"].ToString()并将其存储在字符串变量中来访问单个列.
我想逐行阅读这些列.
谢谢你的帮助.
小智 10
如果要将行和列存储到某种类型的集合中,可以尝试使用List和Dictionary,它可以根据需要添加任意数量的行.
List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();
Dictionary<string, string> column;
string sqlQuery = "SELECT USER_ID, FIRSTNAME, LASTNAME FROM USERS";
SqlCommand command = new SqlCommand(sqlQuery, myConnection);
try
{
myConnection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{ //Every new row will create a new dictionary that holds the columns
column = new Dictionary<string, string>();
column["USER_ID"] = reader["USER_ID"].ToString();
column["FIRSTNAME"] = reader["FIRSTNAME"].ToString();
column["LASTNAME"] = reader["LASTNAME"].ToString();
rows.Add(column); //Place the dictionary into the list
}
reader.Close();
}
catch (Exception ex)
{
//If an exception occurs, write it to the console
Console.WriteLine(ex.ToString());
}
finally
{
myConnection.Close();
}
//Once you've read the rows into the collection you can loop through to
//display the results
foreach(Dictionary<string, string> column in rows)
{
Console.Write(column["USER_ID"]) + " ";
Console.Write(column["FIRSTNAME"] + " ";
Console.Write(column["LASTNAME"] + " ";
Console.WriteLine();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22750 次 |
| 最近记录: |