.Net simplest possible MSSQL database connection

We’re all using ORMS/Micro ORMS/some other framework to abstract away the data layer so I had to remind myself of how to connect to a database the ‘old-fashioned’ way.

using System;
using System.Data.SqlClient;

namespace DBConnTest
{
    class DataBaseConnection
    {
        static void Main(string[] args)
        {
            const string connStr = @"Data Source=XXXX\XXXX, [XXX];Database=XXXXX; Integrated Security=SSPI;";

            using (var conn = new SqlConnection(connStr))
            {
                var cmd = new SqlCommand("select..", conn) { CommandTimeout = 400 };
                conn.Open();

                var dataReader = cmd.ExecuteReader();

                while (dataReader.Read())
                {
                    Console.WriteLine(dataReader[0].ToString());
                    // ...
                }

            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *