C# connect to database and list the databases [duplicate] C# connect to database and list the databases [duplicate] database database

C# connect to database and list the databases [duplicate]


You can use SqlConnection.GetSchema:

using(var con = new SqlConnection("Data Source=Yourserver; Integrated Security=True;")){    con.Open();    DataTable databases = con.GetSchema("Databases");    foreach (DataRow database in databases.Rows)    {        String databaseName = database.Field<String>("database_name");        short dbID = database.Field<short>("dbid");        DateTime creationDate = database.Field<DateTime>("create_date");    }} 

SQL Server Schema Collections (ADO.NET)

To determine the list of supported schema collections, call the GetSchema method with no arguments, or with the schema collection name "MetaDataCollections". This will return a DataTable with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use.


You can write a stored proc which can return you a list of databases on that server.

SELECT nameFROM master.sys.databases

or

EXEC sp_databases


This should get you database names:

var connectionString = string.Format("Data Source=localhost;User ID={0};Password={1};", userName, password);DataTable databases = null;using (var sqlConnection = new SqlConnection(connectionString)){    sqlConnection.Open();    databases = sqlConnection.GetSchema("Databases");    sqlConnection.Close();}if (databases != null){    foreach (DataRow row in databases.Rows)    {        foreach (var item in row.ItemArray)        {            Console.Write("{0} ", item);        }        Console.WriteLine();    }}

Feel free to exclude all the printing at the end. Toss all that in a console app to see it in action. The table names are in index 0 of row.ItemArray.