17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Connecting in C#<br />

C# is a fairly clean language and is relatively easy to learn, much like VB, but it has the extra benefit of<br />

providing some C-based concepts and also being much closer in syntax (making it easier to transition<br />

between the two).<br />

Returning a Data Set<br />

using System;<br />

using System.Data.SqlClient;<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

//Create some base strings so you can look at these<br />

// separately from the commands they run in<br />

// Integrated Security - next line should be uncommented to use<br />

string strConnect = “Data Source=(local);Initial Catalog=master;Integrated<br />

Security=SSPI”;<br />

// <strong>SQL</strong> Security - next line should be uncommented to use<br />

//string strConnect = “Data Source=(local);Initial Catalog=master;User<br />

Id=sa;Password=MyPass”;<br />

string strCommand = “SELECT Name, database_id as ID FROM sys.databases”;<br />

SqlDataReader rsMyRS = null;<br />

SqlConnection cnMyConn = new SqlConnection(strConnect);<br />

try<br />

{<br />

}<br />

Appendix B: Very Simple Connectivity Examples<br />

// “Open” the connection (this is the first time it actually<br />

// contacts the database server)<br />

cnMyConn.Open();<br />

// Create the command object now<br />

SqlCommand sqlMyCommand = new SqlCommand(strCommand, cnMyConn);<br />

// Create the result set<br />

rsMyRS = sqlMyCommand.ExecuteReader();<br />

//Output what we got<br />

while (rsMyRS.Read())<br />

{<br />

// Write out the first (ordinal numbers here)<br />

// column. We can also refer to the column by name<br />

Console.WriteLine(rsMyRS[“Name”]);<br />

}<br />

Console.WriteLine();<br />

Console.WriteLine(“Press any key to continue...”);<br />

Console.ReadKey();<br />

651

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!