Monday, June 18, 2012

SQL Connection in C# (SqlConnection)

I have a simple SQL script which I need to run on SQL server using C#. The script returns an integer. The best way to do it in C# is to use SqlConnection, SqlCommand and SqlDataReader classes.
Here is the source code how we do it in C#:
using (SqlConnection sqlConnection = 
 new SqlConnection(@"Data Source=SERVER_NAME;Initial Catalog=TABLE_NAME;Integrated Security=True"))
 {
    sqlConnection.Open();
    using (SqlCommand sqlCommand = thisConnection.CreateCommand())
    {
        sqlCommand.CommandText = "SELECT MAX(Salary) Salary FROM STUFF";
    }
    using (SqlDataReader reader = thisCommand.ExecuteReader())
    {
        reader.Read();
        Int32 maxSalary = (Int32)reader["Salary"];
    }
}
As I said before if all you need is to run simple SQL script then this is the best approach for you.
But, If your application will work closely to database, updating and fetching data, then I suggest you to use LINQ to SQL Classes Generation in Visual Studio 2010.

2 comments:

  1. Good post for beginners ..... nice structured

    ReplyDelete
  2. straight forward and concise.
    thank yoi

    ReplyDelete