C#Windows窗体应用程序在后台执行SQL查询并在消息框中显示resukt [英] C# Windows Forms Application to Execute SQL Query in the Background and Show the resukt in Message Box

查看:119
本文介绍了C#Windows窗体应用程序在后台执行SQL查询并在消息框中显示resukt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,我有一个C#Windows控制台应用程序,它将执行SQL查询并在控制台中显示输出。我需要在Windows窗体应用程序中实现相同的程序。所以Query应该在后台执行,输出也应该在windows Form和Message框中给出。



我拥有的控制台应用程序是: -

I have a C# Windows Console Application Which will execute an SQL Query and display the output in the console. I need to implement the same program in Windows Forms Application. So that the Query should execute in the Background and the output should be given in the windows Form and Message box as well.

The console application which i have is:-

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace LeakLocationFinder
{
 class Program
 {
     public static void sleep(int ms)
     {
         DateTime startTime_loc = DateTime.Now;
         DateTime stopTime_loc;
         TimeSpan duration_loc;
         do
         {
             stopTime_loc = DateTime.Now;
             duration_loc = stopTime_loc - startTime_loc;
         } while ((duration_loc.TotalMilliseconds < ms) && (!Console.KeyAvailable)); ;
     }
  static void Main(string[] args)
  {
   // Create the connection to the resource!
   // This is the connection, that is established and
   // will be available throughout this block.
     
          using (SqlConnection conn = new SqlConnection())
          {
              // Create the connectionString
              // Trusted_Connection is used to denote the connection uses Windows Authentication
              conn.ConnectionString = "server=(local);database=modelDb;user id=sa;pwd=Esi2008*";
              conn.Open();

              // Create the command
              SqlCommand command = new SqlCommand("DECLARE @var varchar(1000) = (SELECT TOP 1 Text FROM Alarms WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC) DECLARE @start_position int, @end_position int SELECT @start_position = PATINDEX('% at%', @var) SELECT @end_position = PATINDEX('%kilometers%', @var) DECLARE @VALUE VARCHAR(10) = (Select SUBSTRING(@var, @start_position+5,5)) Select Top 1 @VALUE,RouteTable.Latitude,Routetable.Longitude,Alarms.EventTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC", conn);

              /* Get the rows and display on the screen! 
               * This section of the code has the basic code
               * that will display the content from the Database Table
               * on the screen using an SqlDataReader. */
              do
              {
                  using (SqlDataReader reader = command.ExecuteReader())
                  {
                      Console.WriteLine("Leak Location\t\t  Latitude\t\t Longitude\t\t Leak Occured Time");
                      while (reader.Read())
                      {
                          Console.WriteLine(String.Format("{0}\t\t |\t{1}\t|\t{2}\t|\t{3}", reader[0], reader[1], reader[2], reader[3]));
                      }
                  }
                  sleep(5000);
                  Console.Clear();
              }
              while (!Console.KeyAvailable);
              {
                 Console.ReadKey(false);
              }
          }
          }
      }
    }

推荐答案

I建议采取以下步骤:



1)创建一个新的c#winforms applikation。

2)如果你需要手动启动或停止查询添加一个按钮来执行此操作。

3)在表单中添加一个计时器和一个后台工作程序。

4)将timmerintervall设置为30秒并启动每个后台工作程序定时器计时器滴答。

5)将查询放入backgroundworker并将每行放入List< string>

6)添加backgroundworker.RunWorkerCompleted - event。

7)添加一个新表单,在表单上放置一个结果列表框。

8)在第二个表单中添加一个按钮来关闭它或者自动关闭计时器

9)现在你有一些不同的方法可以将查询结果输入你的第二个表单。也许这是最容易的,如果你把列表框公开为第二种形式。

10)你的主要形式的代码可能是这样的:

I'd suggest the follwing steps:

1) create a new c# winforms applikation.
2) if you need to manualy start or stop the query add a button to do so.
3) add a timer and a backgroundworker to your form.
4) set the timmerintervall to 30 seconds and start the backgroundworker each timer the timer ticks.
5) put the query inside the backgroundworker and put each line into a List<string>
6) add the backgroundworker.RunWorkerCompleted - event.
7) add a new form on which you put a listbox for the result.
8) add a button to your second form to close it or a timer for autoclose
9) now you have some different ways to get the query result into your second form. maybe it's the easiest if you make the listbox in second form public.
10) your code in your primary form might be sth like this:
void Button1Click(object sender, EventArgs e)
{
	backgroundWorker1.RunWorkerAsync()
}

void BackgroundWorker1DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
	List<string> liste=new List<string>();
	using (SqlConnection conn = new SqlConnection())
  	{
          // Create the connectionString
          // Trusted_Connection is used to denote the connection uses Windows Authentication
          conn.ConnectionString = "server=(local);database=modelDb;user id=sa;pwd=Esi2008*";
          conn.Open();

          // Create the command
          SqlCommand command = new SqlCommand("DECLARE @var varchar(1000) = (SELECT TOP 1 Text FROM Alarms WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC) DECLARE @start_position int, @end_position int SELECT @start_position = PATINDEX('% at%', @var) SELECT @end_position = PATINDEX('%kilometers%', @var) DECLARE @VALUE VARCHAR(10) = (Select SUBSTRING(@var, @start_position+5,5)) Select Top 1 @VALUE,RouteTable.Latitude,Routetable.Longitude,Alarms.EventTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC", conn);
          do
          {
              using (SqlDataReader reader = command.ExecuteReader())
              {
                  liste.Add("Leak Location\t\t  Latitude\t\t Longitude\t\t Leak Occured Time");
                  while (reader.Read())
                  {
                      liste.Add(String.Format("{0}\t\t |\t{1}\t|\t{2}\t|\t{3}", reader[0], reader[1], reader[2], reader[3]));
                  }
              }
          }
	 }
	e.Result=liste;			 
}
		
void BackgroundWorker1RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
		{

			Form2 form2=new Form2();
			form2.Show();
			foreach(string s in (List<string>e.Result) form2.listBox1.Items.Add(s);			
		}



其中Form2是你的第二个表格并听取列出< string>以及查询结果中的所有行。每次查询运行时都会打开一个新的弹出窗口。


where Form2 is your second Form and liste the List<string> with all the lines from query result. This would open a new popup form each time the query runs.


这篇关于C#Windows窗体应用程序在后台执行SQL查询并在消息框中显示resukt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆