Skip to content

Instantly share code, notes, and snippets.

@trexx
Created November 11, 2021 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trexx/63bcb7e5a81fffce502a65c86bd77c55 to your computer and use it in GitHub Desktop.
Save trexx/63bcb7e5a81fffce502a65c86bd77c55 to your computer and use it in GitHub Desktop.
Simple DB Connection
using System;
using Microsoft.Data.SqlClient;
using System.Text;
namespace sqltest
{
class Program
{
static void Main(string[] args)
{
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.ConnectionString = "Server=<SERVER>;Database=<DATABASE>;Trusted_Connection=True;MultipleActiveResultSets=True";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("\nOpening Database Connection");
connection.Open();
Console.WriteLine("\nSuccess");
String sql = "SELECT name, collation_name FROM sys.databases";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nDone. Press enter.");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment