2017-09-13 47 views
1
**public static void göster() 
    { 
     SqlConnection connection =GetConnection.GetConnectionObject(); 


     //TODO parametreleri command.parameters yoluyla alsın 
     SqlCommand command = new SqlCommand(); 
     command.CommandText= "select * from windowsserv"; 
     command.Connection = connection; 
     if (connection.State != ConnectionState.Open) 
      connection.Open(); 
     Console.WriteLine("Connection opened"); 
     SqlDataReader rdr = command.ExecuteReader(); 

     while(rdr.Read()) 
     { 
    ------------------> Console.WriteLine(rdr[0].ToString()+"--"+rdr[1].ToString()); 

     } 

     if (connection.State != ConnectionState.Closed) 
      connection.Close(); 
     Console.WriteLine("Connection Closed."); 
     Console.ReadLine(); 

    } 

大家好,這是我的代碼,也有更多的ı沒有顯示,我記錄數據到SQL Server。這個代碼塊(用箭頭指出)顯示所有的sql server數據,並且希望在控制檯中只看到最後的數據(記錄到sql server)。但是我找不到任何答案。請幫助。**與SQL使用ado .net的Windows服務集成

+0

這是一個很奇怪的問題。從你的問題中不可能告訴「最後數據」的定義應該是什麼。 –

回答

0

在這一行

command.CommandText= "select * from windowsserv"; 

你可以使用一些SQL過濾器和排序,如:(這將基於日期過濾器返回過去10寄存器..現在你需要知道你的範圍(最後的數據)已經被記錄,達到您所需要的。 更換(date_column)在你的表中的列誰擁有這種類型的數據。

select top 10 * from windowsserv where (date_column) between '2017-09-12 00:00:00' and '2017-09-13 00:00:00' order by (date_column) DESC 

然後在你的代碼,就會有這樣的事情:

SqlCommand command = new SqlCommand(); 
command.CommandText = "select * from select top 10 * from windowsserv where (date_column) between \'2017-09-12 00:00:00\' and \'2017-09-13 00:00:00\' order by (date_column) DESC"; 

你可以提高你的代碼,以及這樣做:

 using (SqlConnection connection = GetConnection.GetConnectionObject()) 
     { 
      //TODO parametreleri command.parameters yoluyla alsın 
      var command = new SqlCommand 
      { 
       CommandText = "select * from windowsserv", 
       Connection = connection 
      }; 

      if (connection.State != ConnectionState.Open) 
       connection.Open(); 

      Console.WriteLine("Connection opened"); 
      var rdr = command.ExecuteReader(); 

      while (rdr.Read()) 
      { 
       Console.WriteLine(rdr[0] + "--" + rdr[1]); 
      } 
     } 
+1

非常感謝您的推薦,並且還使用了SQL過濾器。我的新代碼塊是「」「」command.CommandText =從windowsserv order by date des中選擇top 1 *;「」「」「」instead「」「」「」command.CommandText = select * from windowsserv「;」「」「 」。 –

0

嘗試改變你的while循環。

bool isLast = rdr.Read(); 
    while(isLast) 
    { 
     string firstCol = rdr[0].ToString(); 
     string secondCol = rdr[1].ToString(); 
     isLast = rdr.Read(); 
     if(!isLast) 
     { 
      Console.WriteLine(firstCol+"--"+secondCol); 
      break; 
     } 
    }