Sie sind auf Seite 1von 3

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;ui =sa;!w =12"#"$; SqlCon.%!en($; System.Data.SqlClient.SqlComman SqlCom = new System.Data.SqlClient.SqlComman ($; SqlCom.Connection = SqlCon; SqlCom.Comman &y!e = Comman &y!e.Store 'roce ure; SqlCom.Comman &e(t = "s!) ata*ases"; System.Data.SqlClient.SqlData+ea er SqlD+; SqlD+ = SqlCom.,(ecute+ea er($; w-ile(SqlD+.+ea ($$ . /essa0e1o(.S-ow(SqlD+.2etStrin0(0$$; 3

Don t forget to change the connection string to match your server details !"#, userid and password$% u need to do soket programming using System%&et%Sockets the code is something like below%%% static public S'lServer"nfo() Seek!$ * Socket socket + new Socket!,ddress-amily%"nter&etwork, SocketType%Dgram, #rotocolType%.dp$/ socket%SetSocket0ption!Socket0ptionLevel%Socket, Socket0ption&ame%1roadcast, 2$/ socket%SetSocket0ption!Socket0ptionLevel%Socket, Socket0ption&ame%3eceiveTimeout, 4555$/ 66 -or %&et v 7%5 it888 s a bit simpler 66 socket%9nable1roadcast + true/ 66 for %&et v7%5 66 socket%3eceiveTimeout + 4555/ 66 for %&et v7%5 ,rrayList servers + new ,rrayList!$/ try * byte() msg + new byte() * 5x57 :/ "#9nd#oint ep + new "#9nd#oint!"#,ddress%1roadcast, 2;4;$/ socket%SendTo!msg, ep$/

int cnt + 5/ byte() byt1uffer + new byte(257;)/ do * cnt + socket%3eceive!byt1uffer$/ servers%,dd!new S'lServer"nfo!null, byt1uffer$$/ socket%SetSocket0ption!Socket0ptionLevel%Socket, Socket0ption&ame%3eceiveTimeout, 455$/ : while !cnt <+ 5$/ : catch !Socket9xception socex$ * const int =S,9T">9D0.T + 255?5/ 66 @onnection timed out% const int =S,9A0ST.&39,@A + 255?B/ 66 &o route to host% 66 3eCthrow if it888 s not a timeout% if !socex%9rror@ode ++ =S,9T">9D0.T DD socex%9rror@ode ++ =S,9A0ST.&39,@A$ * 66 D0 nothing%%%%%% : else * 66 @onsole%=riteLine!888E*5: *2:888E, socex%9rror@ode, socex%>essage$/ throw/ : : finally * socket%@lose!$/ : 66 @opy from the untyped but expandable ,rrayList, to a 66 typeCsafe but fixed array of S'lServer"nfos% S'lServer"nfo() aServers + new S'lServer"nfo(servers%@ount)/ servers%@opyTo!aServers$/ return aServers/ : FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 0r !when using %&9T 7%5$ you could Gust use the build in function 8ESystem%Data%S'l%S'lDataSource9numerator8E this wil give you a list off all available SQL Servers in the network% =orks like this:

using System%Data/ using System%Data%S'l/ S'lDataSource9numerator servers + S'lDataSource9numerator%"nstance/ DataTable serversTable + servers%HetDataSource!$/ foreach!Data3ow row in serversTable%3ows$ * string server&ame + string%format!8E*5:8888*2:8E, row(5), row(2)/ 66 ,dd this to your list :