SQL C#

List All SQL Databases

This C# program demonstrates how to list all SQL databases for Microsoft SQL in C#.

Program.cs

using System;
using System.Data.SqlClient;

namespace ListDatabases {
    class Program {
        static void Main(string[] args) {
            ListDatebases();
        }

        public static void ListDatebases() {
            // The using block ensures that the connection is closed when it exits this block.
            using (SqlConnection qConnection = new SqlConnection(
                    @"Server=localhost\SQLEXPRESS01;Trusted_Connection=True;")) {
                qConnection.Open();
                using (SqlCommand qCommand = new SqlCommand(
                	@"SELECT name FROM sys.databases", qConnection)) {
                    using (SqlDataReader qReader = qCommand.ExecuteReader()) {
                        while (qReader.Read()) {
                            Console.WriteLine(qReader[0].ToString());
                        }
                    }
                }
            }
        }
    }
}
 

Output

master
tempdb
model
msdb
xoax
catholic
Press any key to continue . . .
 

Databases

Databases
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.