我有这个代码
string query = "SELECT * FROM table;"
try
{
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(query, connection))
{
SqlDataReader reader = cmd.ExecuteReader();
}
connection.Close();
}
}
在阅读器中,我收到表中的行数,但没有数据。我在哪里迷路了?
调用ExecuteReader
后,您需要遍历它,读取每一行:
while(reader.Read())
{
// Process the row...
}
此外,将读者放入using
块中也是一种很好的做法:
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// Process the row
}
}
你需要阅读阅读器
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader#:~:text=To%20retrieve%20data%20using%20a,rows%20from%20a%20data%20source。
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//
}
}