Easiest Way to Run SQL Query in C#

Easy and straight forward way to run an MS SQL query in a C# application.

If you are looking to run a simple SQL query from your C# application (console app, winform, web application), I’ve outlined below an easy way to query data from an SQL server and save it into a DataTable. Please note a basic understanding of how SQL queries work is needed. Let’s get started!

The code below is what I believe to be the most straight forward way to get SQL data and save query results into a DataTable, which you can then use to Bind to a GridView, do further filtering, etc.

using System.Data;
using System.Data.SqlClient;

class SqlExamples
{
    private static DataTable FillDataTable()
    {
        // filling datatable with sql query results

        DataTable dt = new DataTable();

        string connectionstring = "Data Source=(localdb);User ID=oscar;Password=reader";
        string query = "SELECT userId as id, name AS Name FROM users.dbo.names ORDER BY name";
        SqlConnection connection = new SqlConnection(connectionstring);
        // open SQL connection with adapter
        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
        adapter.Fill(dt);
        connection.Close();

        return dt;

    }
}