Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Possible Duplicate:
SQL Server query to find all current database names

I am trying to figure out how to list the databases after connecting to the servers without specifying a database first.

sqlConnection1 = new SqlConnection("Server=" + sqlServer + ";Database=" + database +     ";User ID=" + userName + ";Password=" + password + ";Trusted_Connection=False;"); 

So basically what i want is the end user to connect to the sql server, then have a drop down list populated with the list of db's they can connect and query.

Ideas?

like image 740
user1158745 Avatar asked Oct 12 '12 15:10

user1158745


1 Answers

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.

like image 93
Tim Schmelter Avatar answered Oct 23 '22 06:10

Tim Schmelter