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

醉酒当歌 提交于 2019-11-30 03:05:17

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 name
FROM 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.

You can use SMO - SQL Server Management Objects.

This is two sample code in code project:

SQL Server Authentication using SMO

Databases using SMO

The most up to date list of databases will be in the database itself. Why not connect to tempdb as a default database (since you have to connect to something) to start with and then query from master.sys.databases.

select [name] from master.sys.databases

Then you can update your connection string with whatever database is necessary or simply change the db using the ChangeDatabase() method.

e.g. connection.ChangeDatabase(selectedDB);

You could also connect to master, but I like to keep default connections in tempdb as occasionally people forget to change databases before creating objects. I would rather the junk go into tempdb than master since tempdb is recreated when SQL restarts.

You can try with

select * from master.sys.databases
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!