Created
November 11, 2021 18:46
-
-
Save trexx/63bcb7e5a81fffce502a65c86bd77c55 to your computer and use it in GitHub Desktop.
Simple DB Connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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