仿VS的Add Connection功能,获取服务器列表及数据库列表

WBOY
풀어 주다: 2016-06-07 15:06:39
원래의
1231명이 탐색했습니다.

VS中有Add Connection功能的界面,能够搜索到局域网内的服务器,连接上服务器后能够根据用户名和密码获得数据库的列表。看似很复杂的一个功能,其实很简单。 1、获取服务器列表。 VS中提供了SqlDataSourceEnumerator类,命名空间为System.Data.Sql,直接调用

     VS中有Add Connection功能的界面,能够搜索到局域网内的服务器,连接上服务器后能够根据用户名和密码获得数据库的列表。看似很复杂的一个功能,其实很简单。

1、获取服务器列表。

VS中提供了SqlDataSourceEnumerator类,命名空间为System.Data.Sql,直接调用GetDataSource()方法,即可或得服务器列表的DataTable。

代码奉上:

        private void GetServerName()
        {
            List<string> serverList = new List<string>();

            DataTable dataTable = SqlDataSourceEnumerator.Instance.GetDataSources();

            DataRow[] rows = dataTable.Select("", "ServerName,InstanceName Asc");

            foreach (DataRow row in rows)
            {
                string server = row["ServerName"].ToString();
                if (string.IsNullOrEmpty(row["InstanceName"].ToString()) == false)
                {
                    server = server + "\\" + row["InstanceName"].ToString();
                }

                serverList.Add(server);
            }

            this.SetComboBoxItemSource(cbServer, serverList);
        }
</string></string>
로그인 후 복사

 2、获取数据库的所有数据库列表。

这个比较简单,连接上服务器后,连接master数据库,通过查询systemdatabases就可以了。

代码奉上:

        private void GetDataBasesName()
        {
            List<string> dataBaseList = new List<string>();</string></string>
로그인 후 복사
          //获取服务器、用户名和密码,可以自己改改参数。
            string server = this.GetControlText(this.cbServer);
            string uid = this.GetControlText(this.txtUid);
            string pwd = this.GetControlText(this.pbPwd);

            string connString = string.Format("server={0};database=master;uid={1};pwd={2}", server, uid, pwd);
            string sql = "select name from SYSDATABASES order by name";

            SqlConnection conn = new SqlConnection(connString);
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    dataBaseList.Add(reader[0].ToString());
                }
            }
            catch (Exception)
            {
                //throw;
            }
            finally
            {
                conn.Close();
            }

            this.SetComboBoxItemSource(this.cbDataBase, dataBaseList);
        }
로그인 후 복사

如有不当之处,还请大家多多指教。

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!