2012-05-28 27 views
2

我試圖從我的數據庫表中檢索最新的數據。 我正在使用max(columnName),但沒有符合我的喜好的結果。 我不斷收到列名,而不是任何價值的在sql express中查找給定表的最大值

請幫我在這...

代碼檢索最大值是這樣

  dbConnection dbCon = new dbConnection(); 
      con = dbCon.doConnection(); 

      SqlCommand cmd = new SqlCommand(); 


      String query = "select max(studentNo) from studentInfo;"; 
      cmd.Connection = con; 
      cmd.CommandText = query; 
      SqlDataReader reader = cmd.ExecuteReader(); 
      while (reader.Read()) 
      { 
       String x=reader["studentNo"].ToString(); 

      } 

這裏的studentNo是列名其值我需要提取,它是int型 ,同時在我的應用程序上打印字符串x我得到studentNo而不是值。 現在我缺乏線索來解決問題,因爲我找不到任何代碼錯誤。 幫我在這一個

回答

3

問題是你的方式訪問的價值,你可以在這裏改變兩件事。通過索引訪問閱讀器或在查詢中適當地命名列。

select max(studentNo) as StudentNo from studentInfo; 
+0

非常感謝你的幫助 – shunilkarki

0

首先,您需要設置正確的別名做柱:

select max(studentNo) as 'studentNo' from studentInfo; 

第二,你可能要指定一個數據庫表:

select max(studentNo) as studentNo from databaseName..studentInfo; 
+0

非常感謝你的幫助 – shunilkarki

+0

@shunilkarki沒有問題,如果它工作,你應該接受答案:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

1

您需要在應用聚合函數後給你的選擇別名

ie select max(studentNo)as studentInfo

雖然讀取它

String x = reader [「NO」]。ToString();

3

您的查詢輸出一行和一列數據,那麼你可以考慮使用ExecuteScalar()代替ExecuteReader()

dbConnection dbCon = new dbConnection(); 
con = dbCon.doConnection(); 

SqlCommand cmd = new SqlCommand(); 


String query = "select max(studentNo) from studentInfo;"; 
cmd.Connection = con; 
cmd.CommandText = query; 
String x = cmd.ExecuteScalar().ToString(); 
+0

+1 - 更好地使用ADO.NET方法比我的回答。 –