B.3. Connectivity Examples

What we're going to do in this section is provide some hyper (and I do mean in the extreme) examples of how to get connected. For each language, we'll show a couple of examples — one for each of two different kinds of operations (fetching a simple data set and executing a query that does not return a data set).

B.3.1. Connecting in C#

C# is somewhat hard to ignore. When I wrote the last version of this book, C# was really just an up and coming thing. It is a fairly clean language and is relatively easy to learn much like VB, but it has the extra benefit of providing some C-based concepts and also being much closer in syntax (making it easier to transition between the two).

B.3.1.1. Returning a Data Set
using System; using System.Data.SqlClient; class Program { static void Main() { //Create some base strings so you can look at these //separately from the commands they run in //Integrated Security - next line should be uncommented to use string strConnect = "Data Source=(local);Initial Catalog=master;Integrated Security=SSPI"; //SQL Security - next line should be uncommented to use //string strConnect = "Data Source=(local);Initial Catalog=master;User Id=sa;Password=MyPass"; string strCommand = "SELECT Name, database_id as ID FROM sys.databases"; SqlDataReader rsMyRS = null; SqlConnection cnMyConn = new SqlConnection(strConnect); try { // "Open" the connection (this is the first time it actually // contacts the database server) cnMyConn.Open(); // Create ...

Get Professional SQL Server™ 2005 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.