C#: SQL Connection with Reader and Using
Author: jason
Date: 2019-01-20 12:53:52
Category: Technical

Here is a quick an easy code snippet for grabbing query results from a sql database. According to the Microsoft document, when you use "using" you don't have to close or dispose.

https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection?view=netframework-4.7.2

Code


public static void ConnectDatabaseQuery()
{
try
{
//using System.Data.SqlClient
string connectionString =
@"Data Source=.SQL2017;Initial Catalog=master;Integrated Security=True;Connection TimeOut=30";

using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT d.name FROM sys.databases d", con);
command.CommandTimeout = 30;
command.Connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetString(0));
}
}
}
} catch (Exception e)
{
Console.Write(e);
}
}







jason @ jasonthomasfrance.com - www.masterstationlog.com - copyright 2009