[英]Create a visual studio Windows Service application that performs SQL operations
好的,我是Windows Service應用程序的新手。 我正在嘗試在運行SQL語句的Visual Studio 2012上使用C#創建Windows服務應用程序。 我的印象是,我們需要在web.config文件中輸入一個連接字符串,以便我的SQL語句與服務器進行通信。 但是服務應用程序中沒有web.config文件。 我該怎么做呢? 任何鏈接到一個教程或一個教程本身將不勝感激! 我想知道項目結構以及我的應用程序正常運行所需要做的工作。
另外,我有一些SQL查詢需要在多個服務器上運行。 相同的查詢在3台不同的服務器上運行。 是否創建3個連接字符串並連接到3個服務器並以運行方式運行它們?
首先,所有應用程序都具有web.config
或app.config
。 如果要編寫MVC應用程序或Web Forms應用程序,則存在一個web.config
文件。 如果要編寫Windows服務,Windows控制台或桌面應用程序,則將有一個app.config
文件。
連接到SQL Server是一個非常簡單的任務。 您只需使用SqlConnection創建連接。 接下來,創建一個SqlCommand 。 最后,您可以執行SQL查詢。
這是一個例子:
public void DeleteRow()
{
using (var connection = new SqlConnection("your connection string here..."))
{
using (var command = new SqlCommand())
{
command.Connection = connection;
// Next command is your query.
command.CommandText = "DELETE FROM Customers WHERE CustomerId = 1";
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
}
}
如果要執行不返回任何數據的查詢,請使用第一個示例。 如果需要返回數據,請使用如下示例:
public void GetCustomer()
{
using (var connection = new SqlConnection("your connection string here..."))
{
using (var command = new SqlCommand())
{
SqlDataReader reader;
command.Connection = connection;
// Next command is your query.
command.CommandText = "SELECT * FROM Customers WHERE CustomerId = 1";
command.CommandType = CommandType.Text;
connection.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.