Marzouk
Marzouk

Reputation: 2713

Method fires an exception when trying to connect to remote SQL Server

I want to create a simple tool that connect to SQL Server then list all databases, and after user selects one of those databases, the tool will perform some SQL scripts on it.

Below is a method that should return a DataTable contains all my databases; I send to it sqlServerIp as first parameter like 10.10.20.30 ip address not server name.

Also I didn't specify a SQL Server instance.

  private DataTable GetSqlServerDatabases(String sqlServer, bool isWindowsAuth, String login, String password)
  {
        String connectionString;
        DataTable databases;

        if (isWindowsAuth)
        {
            connectionString = "Data Source=" + sqlServer + ",1433;Network Library=DBMSSOCN; Integrated Security=True;";
        }
        else
        {
            connectionString = "Data Source=" + sqlServer + ",1433;Network Library=DBMSSOCN;" + "User id=" + login + ";Password=" + password + ";";
        }

        try
        {
            using (var con = new SqlConnection(connectionString))
            {
                con.Open();
                databases = con.GetSchema("Databases");

                foreach (DataRow database in databases.Rows)
                {
                    String databaseName = database.Field<String>("database_name");
                    short dbID = database.Field<short>("dbid");
                    DateTime creationDate = database.Field<DateTime>("create_date");
                }
            }
        }
        catch(Exception ex)
        {
            databases = null;
            MessageBox.Show(ex.Message.ToString());
        }

        return databases;
    }

When I try to call the method on more than one server I faced an exception:

Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.

or

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.

I used connection string with Network Library=DBMSSOCN; after searching here on SO and web so I don't know what is the wrong with this method.

Upvotes: 0

Views: 80

Answers (1)

Denis Voituron
Denis Voituron

Reputation: 298

Remove Integrated Security parameter. This parameter is for trusted connections.

More samples on http://www.connectionstrings.com/sql-server

Upvotes: 1

Related Questions