繁体   English   中英

使用SqlDataReader从数据库读取

[英]Reading from database using SqlDataReader

G_ID是“组”表中的整数列。 我想要最大的价值。 当我跟踪下面的代码时,我收到代码中提到的错误。 Reader.HasRows在调试期间等于true。 那么为什么说“没有数据”

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;
        }

在访问DataReader之前,您需要调用Read方法将阅读器放置在第一条记录上

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;
}

顺便说一句,您的查询仅从数据库返回一行和一列,因此更好的方法是使用ExecuteScalar方法

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;
}

您正在检查读取器是否有行,但没有读取它们。 改为执行此操作(请注意,我还要包装东西以确保正确处置它们):

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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