[英]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.