简体   繁体   中英

How to get a list of all (remote) database with the server name only?

My requirement is to list all remote databases, but i only know the servername.

I am using below code, this works and returns all of the databases on localhost:

List<String> databases = new List<String>();
SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();
connection.DataSource = "localhost";
connection.IntegratedSecurity = true;
//connection.UserID = "";//
//connection.Password = "";//
String strConn = connection.ToString();
SqlConnection sqlConn = new SqlConnection(strConn);
sqlConn.Open();
DataTable tblDatabases = sqlConn.GetSchema("Databases");
sqlConn.Close();
foreach (System.Data.DataRow row in tblDatabases.Rows)
{
    String strDatabaseName = row["database_name"].ToString();
    databases.Add(strDatabaseName);
}

But how can i get databases on other servers without login informations?

public List<string> GetDatabaseList()
{
    List<string> list = new List<string>();
    string conString = "server=ServerName;uid=sa;pwd=Password;";
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
        {
            using (IDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    list.Add(dr[0].ToString());
                }
            }
        }
    }
    return list;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM