Crazy Cucumber
Crazy Cucumber

Reputation: 479

Create a visual studio Windows Service application that performs SQL operations

Alright, I am new to Windows Service applications. I am trying to create a Windows Service application using C# on Visual Studio 2012 that runs SQL statements. I was under the impression that we needed to enter a connection string in the web.config file for my SQL statements to communicate with the server. But there is no web.config file in a service application. How do I go about doing this? Any links to a tutorial or a tutorial in itself would be appreciated! I want to know the project structure and what I need to do for my application to work right.

Also, I have some SQL queries that need to run on multiple servers. The same queries run on 3 different servers. Does creating 3 connection strings and connecting to the 3 servers and running them the way to do it?

Upvotes: 0

Views: 1817

Answers (1)

Icemanind
Icemanind

Reputation: 48686

First of all, all applications have either a web.config or an app.config. If you are writing an MVC application or a Web Forms applications, then there is a web.config file. If you are writing a Windows service or a Windows Console or Desktop application, you'll have an app.config file instead.

Connecting to SQL Server is a pretty simple task. You just create a connection using SqlConnection. Next, you create a SqlCommand. Finally, you can execute your SQL query.

Here is an example:

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();
        }
    }
}

Use that first example if you are executing queries that return no data. If you need to return data, then use an example like this:

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.                 
        }
    }
}

Upvotes: 1

Related Questions