Created
December 9, 2021 09:10
-
-
Save drikusroor/90294ef4e0bca927def98424956bdfd9 to your computer and use it in GitHub Desktop.
Test multiple SQL Server connection strings in a dotnet console app
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
// Source: https://ainab.site/2021/12/09/test-multiple-sql-server-connection-strings-in-a-dotnet-console-app/ | |
using System.Data.SqlClient; | |
class Credentials | |
{ | |
public string Username { get; set; } | |
public string Password { get; set; } | |
public string Server { get; set; } | |
public Credentials(string username, string password, string server = "sql-server.example.com") { | |
Username = username; | |
Password = password; | |
Server = server; | |
} | |
public string GenerateConnectionString() | |
{ | |
return $"Server=tcp:{Server},1433;Initial Catalog=defaultDatabase;Persist Security Info=False;User ID={Username};Password={Password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
List<Credentials> credentialsCollection = new List<Credentials> | |
{ | |
new Credentials("login-one", "complex-password"), | |
new Credentials("login-two", "complex-password"), | |
new Credentials("login-three", "complex-password") | |
}; | |
foreach (var credentials in credentialsCollection) | |
{ | |
TestConnectionString(credentials); | |
} | |
} | |
// Source: https://stackoverflow.com/a/1497110/4496102 | |
static void TestConnectionString(Credentials credentials) | |
{ | |
SqlConnection? conn = null; | |
var connectionString = credentials.GenerateConnectionString(); | |
try | |
{ | |
conn = new SqlConnection(connectionString); | |
conn.Open(); | |
Console.WriteLine("good connection string"); | |
} | |
catch (SqlException sqlE) | |
{ | |
Console.WriteLine($"bad connection string: {credentials.Username}"); | |
} | |
finally | |
{ | |
if (conn != null) conn.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment