Tuesday, October 26, 2010

Connecting to SQL Server via SMO


When you want to connect to the SQL Server 2005 (or later version), you can use SMO. To get started with SMO, you must first add reference to Visual studio. In Add Reference window select Microsoft.SqlServer.Smo, Microsoft.SqlServer.SmoExtended, Microsoft.SqlServer.Management.Sdk.Sfc, and Microsoft.SqlServer.ConnectionInfo.

After that, you have to add two namespaces, that you will need:

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

Now, you can start working with SMO objects. First object, you need to use is ServerConnection object. This object represents connection to SQL Server instance.

ServerConnection conn = new ServerConnection("INSTANCE", "LOGIN", "PASSWORD");
try
{
    Server srv = new Server(conn);
    Console.WriteLine("Server: " + srv.Name);
    Console.WriteLine("Edition: " + srv.Information.Edition);

}
catch (Exception err)
{
    Console.WriteLine(err.Message);
}

you can also use windows integrated authentication:

ServerConnection conn = new ServerConnection();
conn.ServerInstance = "INSTANCE";
try
{
    Server srv = new Server(conn);
    Console.WriteLine("Server: " + srv.Name);
    Console.WriteLine("Edition: " + srv.Information.Edition);

}
catch (Exception err)
{
    Console.WriteLine(err.Message);
}

No comments:

Post a Comment