Search code examples
c#sqlvisual-studioconnectionlan

How to Connect to SQL Server Programmatically in C#?


I have developed a program (C#) which creates a SQL database using this code:

string SQLCreation = "IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE Name = 'x') CREATE DATABASE x";
SqlConnection PublicSQLDBCreationConnection = new SqlConnection(connectionString);
SqlCommand PublicSQLDBCreation = new SqlCommand(SQLCreation, PublicSQLDBCreationConnection);

try
{
   PublicSQLDBCreationConnection.Open();
   PublicSQLDBCreation.ExecuteNonQuery();
   PublicSQLDBCreationConnection.Close();
}
//'then creates a table and so on

Now I want to have a client application which connects to this database (via LAN) WITHOUT using IP or computer name. How is that possible? Is it possible do this and have a dataset while not mentioning IP Adr. or computer name?


P.S. Don't Worry Guys, I simplified my code just for your view, I have made sure that SQL injection or other attempts won't happen. Also I have to say that My Reason for not mentioning servername or IP is that I want to mass deploy my Application on many Networks


Solution

  • You could use SqlDataSourceEnumerator to get a list of all Sql Servers that are visible and browsable. This is not a good technique, since you could get an instance that you don't have the right to create a database on it, but you could still try something with that.

    var enumerator = SqlDataSourceEnumerator.Instance;
    foreach (DataRow row in enumerator.GetDataSources().Rows)
    {
        var serverName = row["ServerName"];
        var instance = row["InstanceName"];
    
        // build a connection string and try to connect to it
    }