Simple Connected DB Example
The following code can be copied and compiled in a C# commandline project:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace SimpleConnected { /// <summary> /// This simple program demonstrates how to access rows of data from a /// database using SQL commands in a connected scenario. /// </summary> class Program { static void Main(string[] args) { /* * First we have to identify the server and how we will connect to * it. The "Data Source" gives the name and instance of the server * which in this case is the SQLExpress instance on the localhost. * The "Initial Catalog" identifies the Database. We could use a * username and password if we had used database security. But in * this case we used "Security Support Provider Interface" (SSPI) * to authenticate the currently logged in user. */ string constr = @"Data Source=localhost\SQLExpress; Initial Catalog=VRG; Integrated Security=SSPI;"; /* * The above is just a string, we still need a connection to the * database. We do this using the SqlConnection object from * System.Data.SqlClient (see the using statement) * We feed the SqlConnection object the connection string so that * it knows what to connect to and how. */ SqlConnection con = new SqlConnection(constr); /* * The connection isn't much good unless you open it. This opens * the connection so that we can execute commands against it. */ con.Open(); /* * Now that we have an open connection, lets look at how we can use * it. TO do this we create a SqlCommand object, again from * System.Data.SqlClient * In order for the Command object to do much it has to have access * to the connection object so we define the command using SQL and * give it the connection. */ SqlCommand com = new SqlCommand("SELECT * FROM Customer",con); /* * There are other options that we could give command, but this is * enough to start. The command doesn't execute until you actually * tell it to, which we do next. We can execute it in several * different ways. Lets use the command completion to look at some * of them... */ SqlDataReader sdr = com.ExecuteReader(); /* * Since we chose to get a DataReader we can now loop through the * rows in the database */ while (sdr.Read()) { /* * The rows are accessed directly from the DataReader using * either an integer or string index. Here I've actually * trimmed the results so that I don't get fixed length strings */ Console.WriteLine("Name: {0}, Email: {1}", sdr["Name"].ToString().Trim(), sdr["Email"].ToString().Trim()); } /* * Don't forget to clean up after yourself! */ sdr.Close(); con.Close(); } } }