Well, there are two ways to interact with a SQL Server database in C #. The first is with LINQ, and the second is with the SqlClient library.
LINQ
Since the release of .NET 3.0, we have had access to LINQ, which is a pretty impressive ORM and way to handle collections and lists. There are two different ways that LINQ can work with a database. It:
Scott Gu has a good LINQ to SQL tutorial. I would recommend LINQ to SQL just for starters, and you can use a lot of LINQ to Entities in the future.
Sample select to capture all clients in New York:
var Custs = from c in Customers where c.State = 'NY' select c; foreach(var Cust in Custs) { Console.WriteLine(Cust.Name); }
Sqlclient
The traditional C # way to access the SQL Server database (pre-.NET 3.0) was through the SqlClient library . Essentially, you create an SqlConnection to open a database connection. If you need help with connection strings, check ConnectionStrings.com .
After you connect to your database, you will use the SqlCommand object to interact with it. The most important property for this object is CommandText . It accepts SQL as its language and will run raw SQL statements in the database.
If you insert / update / delete, you use the ExecuteNonQuery SqlCommand method. However, if you make a choice, you will use ExecuteReader and return SqlDataReader . You can then iterate through SqlDataReader to get the results.
Below is the code to capture all customers in New York again:
using System.Data; using System.Data.SqlClient; //... SqlConnection dbConn = new SqlConnection("Data Source=localhost;Initial Catalog=MyDB;Integrated Security=SSPI"); SqlCommand dbComm = new SqlCommand(); SqlDataReader dbRead; dbConn.Open(); dbComm.Connection = dbConn; dbComm.CommandText = "select name from customers where state = @state"; dbComm.Parameters.Add("@state", System.Data.SqlDbType.VarChar); dbComm.Parameters["@state"].Value = "NY"; dbRead = dbComm.ExecuteReader(); if(dbRead.HasRows) { while(dbRead.Read()) { Console.WriteLine(dbRead[0].ToString()); } } dbRead.Close(); dbConn.Close();
Hope this gives you a good idea of what each approach does and how to learn more.