/**================================================================== * an introduction to using databases with C# * Note: this code presumes that you have the Microsoft .Net framework * installed on your machine (Sieg lab machines do, otherwise download from * Microsoft's site). * Command line options: * To Compile: csc Sample.cs (make sure that csc.exe is in your path) * To Run: Sample * Alternatively, you can compile and run using MSVC .Net ======================================================================*/ /** * the using statements are analogous to Java's * include and C++'s import directives * you almost always want the System package (it contains the * most basic classes); whenever you use a database you need to * also import a package that contains those classes * Alternatively, as in Java and C++, you can use the full name */ using System; using System.Data.SqlClient; public class Sample{ /**the string that says where you're connecting * authenticates you to the DBMS and specifies which * database you will be using (the latter is optional--each user has * a default database that will be used if this option is omitted) * I have creates a generic cse444_student user so you can run this * code as is */ static string strConnection="server=ISQL01;uid=cse444_student;password=cse444_student;database=cse444_hwk"; /* the connection object*/ static SqlConnection _con; /* the connection object*/ static SqlCommand cmdSql; /* the connection object*/ static SqlDataReader drResultSet; public static void Main(string[] argv){ /* instantiate the connection and command objects * associate the command with this connection*/ try{ _con = new SqlConnection (strConnection ); cmdSql= new SqlCommand(); cmdSql.Connection=_con ; }catch (Exception e){ Console.WriteLine("Failure "+e.ToString()); } /* create the query you want to issue * and associate it with the command object*/ string query="SELECT * FROM Movies"; cmdSql.CommandText=query; /* Open the connection and issue the query */ _con.Open(); drResultSet=cmdSql.ExecuteReader(); /* time to traverse the result set: * remember cursors from lecture? * by default, the cursor is positioned *before* * the first entry of the ResultSet, so you need * to advance at least once by calling Read() * before you try to access any data*/ while(drResultSet.Read()){ Console.Write(drResultSet["Title"]+"\t"); Console.Write(drResultSet["Rating"]+"\t"); Console.WriteLine(drResultSet["Length"]); } //just used to prevent window from closing Console.ReadLine(); } }