How to get a list of SQL Server databases

How to get a list of SQL Server databases

There are multiple ways of getting a list of the SQL Server databases, the easiest one is to execute the sp_databases stored procedure, like in the example below:

System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=192.168.0.1;uid=sa;pwd=1234");
SqlCon.Open();
System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases";

System.Data.SqlClient.SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();

while(SqlDR.Read())
{
MessageBox.Show(SqlDR.GetString(0));
}

Don’t forget to change the connection string to match your server details (IP, userid and password).

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top