Trying to improve my C# to SQL skills… Currently I am using this bit of code to pull data from our application server. I have two different DBA’s telling me two other ways to write this, just trying to figure out if this should be improved on or changed. If so, I would really appreciate some kind of examples.
FYI: This code…
db.con(user.Authority)
…Is essentially a ‘new sqlconnection’ code.
DataTable dtInfo = new DataTable("SomeInfo");
using (SqlConnection con = db.con(user.Authority))
{
string command = "SOME SQL STATEMENT;";
using (SqlCommand cmd = new SqlCommand(command,con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Param", sqlDbType).Value = Param;
con.Open();
cmd.ExecuteNonQuery();
**********
*** OR ***
**********
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Param", sqlDbType).Value = Param;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dtInfo );
}
}
}
So, if I’m understanding the provided information, this is my best route?
using (SqlConnection con = db.con(user.Authority))
{
string command = "SELECT [TBL_EMPLOYEE].[ACTIVE_DIRECTORY] FROM [TBL_EMPLOYEE];";
using (SqlCommand cmd = new SqlCommand(command, con))
{
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader["ACTIVE_DIRECTORY"].ToString());
}
}
}
And one last thing… This should prevent the need for
cmd.Dispose();
etc...
I would not use the
SqlDataAdapterversion. The version that uses theSqlCommandobject and theSqlDataReaderwill perform better, and allows more insight into the actual data being returned.Later as your level of experiance increases you will be able to use other features of the
SqlCommandandSqlDataReaderclasses in order to ensure that the code executes as quickly as possible. If you start using theSqlDataAdapterroute, you will eventually have to relearn how to do the exact same things you have already been doing because theSqlCommandandSqlDataReaderhave operations that do not exist elsewhere in .NET.