tags:

views:

224

answers:

4

This is a really, really stupid question but I am so accustomed to using linq / other methods for connecting and querying a database that I never stopped to learn how to do it from the ground up.

Question: How do I establish a manual connection to a database and pass it a string param in C#? (yes, I know.. pure ignorance).

Thanks

+1  A: 

One uses the SqlCommand class to execute commands (either stored procedures or sql) on SQL Server using ado.net. Tutorials abound.

Ken Browning
Thanks - I attempted to search for it but was getting a wide range of results, none of which seemed to be what I was looking for. the SqlCommand class certainly narrows down my search. Thanks
Chance
+1  A: 

Here's an example from http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx

public void RunStoredProcParams()
    {
     SqlConnection conn = null;
     SqlDataReader rdr  = null;

     // typically obtained from user
     // input, but we take a short cut
     string custId = "FURIB";

     Console.WriteLine("\nCustomer Order History:\n");

     try
     {
      // create and open a connection object
      conn = new 
       SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
      conn.Open();

      // 1.  create a command object identifying
      //     the stored procedure
      SqlCommand cmd  = new SqlCommand(
       "CustOrderHist", conn);

      // 2. set the command object so it knows
      //    to execute a stored procedure
      cmd.CommandType = CommandType.StoredProcedure;

      // 3. add parameter to command, which
      //    will be passed to the stored procedure
      cmd.Parameters.Add(
       new SqlParameter("@CustomerID", custId));

      // execute the command
      rdr = cmd.ExecuteReader();

      // iterate through results, printing each to console
      while (rdr.Read())
      {
       Console.WriteLine(
        "Product: {0,-35} Total: {1,2}",
        rdr["ProductName"],
        rdr["Total"]);
      }
     }
     finally
     {
      if (conn != null)
      {
       conn.Close();
      }
      if (rdr != null)
      {
       rdr.Close();
      }
     } 
    }
John Boker
Thanks man, thats exactly what I was looking for.
Chance
An improvement to this example is to use the "using" keyword to automatically dispose of Connection, Command and Reader instances.
Ken Browning
Also: setting explicit data types for the query parameters.
Joel Coehoorn
+3  A: 
using (SqlConnection conn = new SqlConnection(databaseConnectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "StoredProcedureName";
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr =
                   cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (rdr.Read())
            {
                // process row from resultset;
            }
        }
    }
}
Mitch Wheat
+1  A: 

3 things no one else has shown you yet:

  • "Stacking" using statements
  • Setting an explicit parameter type rather than letting .Net try to pick one for you
  • "var" keyword

.

string sql = "MyProcedureName";

using (var cn = new SqlConnection(databaseConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@ParameterName", SqlDbType.VarChar, 50)
        .Value = "MyParameterValue";

    conn.Open();
    using (SqlDataReader rdr =
               cmd.ExecuteReader(CommandBehavior.CloseConnection))
    {
        if (rdr.Read())
        {
            // process row from resultset;
        }
    }
}
Joel Coehoorn