Skip to content

Instantly share code, notes, and snippets.

@drikusroor
Created December 9, 2021 09:10
Show Gist options
  • Save drikusroor/90294ef4e0bca927def98424956bdfd9 to your computer and use it in GitHub Desktop.
Save drikusroor/90294ef4e0bca927def98424956bdfd9 to your computer and use it in GitHub Desktop.
Test multiple SQL Server connection strings in a dotnet console app
// 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