C#连接到远程SQL Server并获取数据库

时间:2014-01-09 22:12:03

标签: c# sql sql-server database-connection

我目前能够连接到本地SQL Server实例并获取数据库列表。但是,我现在正在尝试连接到远程SQL Server实例并获取其数据库列表。

我似乎无法使SQLConnection正确。

using (var oSQLConnection = new SqlConnection("Data Source=123.45.67.890; User ID=sa; Password=password; ))

以下是我用于本地SQL Server连接的代码。

    private void btSQLListRefresh_Click(object sender, EventArgs e)
    {
        string sDatabaseName = "";
        using (var oSQLConnection = new SqlConnection("Data Source=localhost; Integrated Security=True;"))

        {
            oSQLConnection.Open();
            DataTable oDatabases = oSQLConnection.GetSchema("Databases");
            int iDBCount = oDatabases.Rows.Count;

            foreach (DataRow database in oDatabases.Rows)
            {
                sDatabaseName = database.Field<String>("database_name");
                short sDBID = database.Field<short>("dbid");
                DateTime dCreationDate = database.Field<DateTime>("create_date");

                if (sDatabaseName != "master" && sDatabaseName != "model" && sDatabaseName != "msdb" && sDatabaseName != "tempdb")
                {
                    lbSQLDBList.Items.Add(sDatabaseName);
                }
            }
        }
    }

错误:

  

ServerVersion&#39; oSQLConnection.ServerVersion&#39;抛出类型&#39; System.InvalidOperationException&#39; string {System.InvalidOperationException}

     

base {&#34;无效的操作。连接已关闭。&#34;} System.SystemException {System.InvalidOperationException}

1 个答案:

答案 0 :(得分:0)

试试这个:

数据源= 123.45.67.890.100,+ [IP访问的端口号ex:“1433”];网络库= DBMSSOCN;初始目录=主;用户ID = sa;密码=密码;

我认为你只是缺少一个访问端口号。