简体   繁体   中英

Reading from database using SqlDataReader

G_ID is an integer column in Groups table. I want the maximum value of it. When I trace below code I receive the error I've mentioned in code. Reader.HasRows equals true during debugging. So why it says "no data is present"

SqlConnection sqlc= new SqlConnection("data source=. ; database=LDatabase; integrated security=true");
SqlCommand cmd= new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);

sqlc.Open();
SqlDataReader Reader= cmd.ExecuteReader();
int MaxID = 0;
        if (Reader.HasRows)
        {
            MaxID = Convert.ToInt32(Reader["MAXID"].ToString());// Here I receive this error:  System.InvalidOperationException: Invalid attempt to read when no data is present.
            MaxID += 1;
        }

Before accessing a DataReader you need to call the method Read to position the reader on the first record

SqlConnection sqlc= new SqlConnection("data source=. ; database=LDatabase; integrated security=true");
SqlCommand cmd= new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);

sqlc.Open();
SqlDataReader Reader= cmd.ExecuteReader();
int MaxID = 0;
if (Reader.Read())
{
    MaxID = Convert.ToInt32(Reader["MAXID"].ToString());
    MaxID += 1;
}

By the way, your query returns just one row and one column from the DB so a better approach is to use the ExecuteScalar method

SqlCommand cmd= new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);
sqlc.Open();
object result = cmd.ExecuteScalar();
if (result != null)
{
    MaxID = Convert.ToInt32(result) + 1;
}

You are checking if the reader has rows but you are not reading them. Do this instead (note I'm also wrapping things to make sure they gets disposed properly):

SqlConnection sqlc= new SqlConnection("data source=. ; database=LDatabase; integrated security=true");
SqlCommand cmd = new SqlCommand("select MAX(G_ID) as MAXID from Groups", sqlc);

sqlc.Open();
try {
    using (SqlDataReader reader = cmd.ExecuteReader()) {
        int MaxID = 0;

        while (reader.Read()) {
            MaxID = Convert.ToInt32(Reader["MAXID"].ToString());
            MaxID += 1;
        }
    }
}
finally {
    sqlc.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM