时间:2021-07-01 10:21:17 帮助过:20人阅读
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);
- }
如有不当之处,还请大家多多指教。