By:Artemakis Artemiou | Last Updated: 2018-11-14 || Related Tips:More > Application Development
ProblemIn one of myprevious tips, I've talked about how you can get started with SQL Server and .NET. In this tip, we are going to see how to query SQL Server tables from .NET, get the results, and process them. More specifically, we are going to continue and further develop the example presented in the previous tip, and see how you can query SQL Server tables via a C# console application.
SolutionAs mentioned above, in this tip we will see how you can run SQL Server queries from within the C# application, as well as how you can process the results. This tip's examples, are related to the example in my previous tip How to Get Started with SQL Server and .NET .
SQL Server Sample DatabaseOur example will be based on the database "SampleDB" which is a sample database I created on a test SQL Server named instance on my local machine. The name of the instance is " SQL2K17 ".
Here's a screenshot of the SQL Server instance, as it can be seen in SSMS:
Image may be NSFW.
Clik here to view.

Also, here's the database diagram of the tables in the "SampleDB" database which will be used for this tip's examples:
Image may be NSFW.
Clik here to view.

As you can see, there is a table named "employees" and another table named "location".
The "employees" table has a foreign key (locationID) pointing to the "location" table and more specifically, to the "id" column.
Sample DataThe sample data in the "location" table are:
Image may be NSFW.
Clik here to view.

The sample data in the "employees" table are:
Image may be NSFW.
Clik here to view.

Connecting to the SQL Server Instance Connection String
We will connect to the SQL Server instance by using a trusted connection. The connection string to be used in this example is:
string connString = @"Server =.\SQL2K17; Database = SampleDB; Trusted_Connection = True;";The above connection string, will allow me to connect to the named instance "SQL2K17" on my local machine, using a trusted connection, which will be established using my windows account.
Executing a SELECT SQL StatementNow, let's run a simple SELECT query, get the results and display them.
The SQL statement that we will execute is the below:
SELECT e.id,e.code,e.firstName,e.lastName,l.code,l.descrFROM employees e
INNER JOIN location l on e.locationID=l.id;
The above SELECT query, returns all the employee records from the sample database, along with the code and description of their location.
So, let's write the required .NET code for executing the above query against the database "SampleDB" on the local named SQL server instance "SQL2K17". Below you can find the code.
Note:Prior to start writing the code, similarly to myprevious tip, you will need to create a new Visual C# project in Visual Studio, and select the "Console App (.NET Framework)" template. In my example, I named the project " TestApp2-SELECT " and saved it in the "C:\temp\demos" folder on my local machine (a new subfolder with the name of the project was created).
Here's the code:
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace TestApp2_SELECT
{
class Program
{
static void Main(string[] args)
{
//set the connection string
string connString = @"Server =.\SQL2K17; Database = SampleDB; Trusted_Connection = True;";
//variables to store the query results
int empID;
string empCode, empFirstName, empLastName, locationCode, locationDescr;
try
{
//sql connection object
using (SqlConnection conn = new SqlConnection(connString))
{
//retrieve the SQL Server instance version
string query = @"SELECT e.id,e.code,e.firstName,e.lastName,l.code,l.descr
FROM employees e
INNER JOIN location l on e.locationID=l.id;
";
//define the SqlCommand object
SqlCommand cmd = new SqlCommand(query, conn);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
Console.WriteLine(Environment.NewLine + "Retrieving data from database..." + Environment.NewLine);
Console.WriteLine("Retrieved records:");
//check if there are records
if (dr.HasRows)
{
while (dr.Read())
{
empID = dr.GetInt32(0);
empCode = dr.GetString(1);
empFirstName = dr.GetString(2);
empLastName = dr.GetString(3);
locationCode = dr.GetString(4);
locationDescr = dr.GetString(5);
//display retrieved record
Console.WriteLine("{0},{1},{2},{3},{4},{5}", empID.ToString(), empCode, empFirstName, empLastName, locationCode, locationDescr);
}
}
else
{
Console.WriteLine("No data found.");
}
//close data reader
dr.Close();
//close connection
conn.Close();
}
}
catch (Exception ex)
{
//display error message
Console.WriteLine("Exception: " + ex.Message);
}
}
}
}
As you can see in the above code, I have used an SqlConnection object in order to set the connection based on the connection string. Then, I used an SqlCommand object and passed as parameters the query and the SqlConnection object. Finally, I used an SqlDataReader object in order to store and then display the query's results.
OK, now that the source code is complete, it's time to compile and run the program. To compile the program, within our project in Visual Studio, by pressing the key F6 or by clicking on the " Build " menu and then click on " Build Solution ", our program will be compiled and if everything is OK, that is if we get no errors and see the "Build succeeded" notification on the bottom left corner of the window, it means that the program is now ready for executio