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).

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top