我在框架 4.0 和 SQL Server 2008 R2 中使用 C#。 我已经使用以下代码列出了 SQL Server 2008:
public static string[] GetSQLServerList()
{
SqlDataSourceEnumerator dse = SqlDataSourceEnumerator.Instance;
DataTable dt = dse.GetDataSources();
if (dt.Rows.Count == 0)
{
return null;
}
string[] SQLServers = new string[dt.Rows.Count];
int f = -1;
foreach (DataRow r in dt.Rows)
{
string SQLServer = r["ServerName"].ToString();
string Instance = r["InstanceName"].ToString();
if (Instance != null && !string.IsNullOrEmpty(Instance))
{
SQLServer += "\\" + Instance;
}
SQLServers[System.Math.Max(System.Threading.Interlocked.Increment(ref f), f - 1)] = SQLServer;
}
Array.Sort(SQLServers);
return SQLServers;
}
我在 ComboBox 上列出了我的服务器。
如何列出数据库,取决于我在 ComboBox 中选择的服务器?
我找到了这个 tutorial ,但是需要sqlconnection
,没有选择服务器怎么连接呢?
最佳答案
这是获取网络上服务器名称列表的方式:
List<String> ServerNames = new List<String>();
SqlDataSourceEnumerator servers = SqlDataSourceEnumerator.Instance;
DataTable serversTable = servers.GetDataSources();
foreach (DataRow row in serversTable.Rows) {
string serverName = row[0].ToString();
try {
if (row[1].ToString() != "") {
serverName += "\\" + row[1].ToString();
}
}
catch {
}
ServerNames.Add(serverName);
}
从所选服务器获取数据库列表:
List<String> databases = new List<String>();
SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();
connection.DataSource = SelectedServer;
// enter credentials if you want
//connection.UserID = //get username;
// connection.Password = //get password;
connection.IntegratedSecurity = true;
String strConn = connection.ToString();
//create connection
SqlConnection sqlConn = new SqlConnection(strConn);
//open connection
sqlConn.Open();
//get databases
DataTable tblDatabases = sqlConn.GetSchema("Databases");
//close connection
sqlConn.Close();
//add to list
foreach (DataRow row in tblDatabases.Rows) {
String strDatabaseName = row["database_name"].ToString();
databases.Add(strDatabaseName);
}
关于c# - 获取数据库列表取决于所选服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686433/