您的当前位置:首页正文

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

来源:独旅网

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

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

1、获取服务器列表。

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

代码奉上:

 private void GetServerName()
 {
 List serverList = new List();

 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);
 }

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

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

代码奉上:

 private void GetDataBasesName()
 {
 List dataBaseList = new List();
     //获取服务器、用户名和密码,可以自己改改参数。
 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);
 }

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

显示全文