1

Using this:

SqlConnection myConnection = new SqlConnection("Data Source=.\\SERVER;Initial Catalog=DB;Integrated Security=True;TrustServerCertificate=True;User Instance=False");
myConnection.Open();

SqlCommand myCommand = new SqlCommand("SELECT BusinessName FROM Businessess WHERE BusinessID = @Param2", myConnection);

SqlParameter myParam2 = new SqlParameter("@Param2", SqlDbType.Int, 4);
myParam2.Value = 1;
myCommand.Parameters.Add(myParam2);

MessageBox.Show(myCommand); //How do I bind results to show as string?

How do I bind the results of a prepared statement to a variable so that I may manipulate them?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dan Kanze
  • 18,485
  • 28
  • 81
  • 134

1 Answers1

6

Try like this:

using (SqlConnection myConnection = new SqlConnection("Data Source=.\\SERVER;Initial Catalog=DB;Integrated Security=True;TrustServerCertificate=True;User Instance=False"))
using (SqlCommand myCommand = myConnection.CreateCommand())
{
    myConnection.Open();
    myCommand.CommandText = "SELECT BusinessName FROM Businessess WHERE BusinessID = @Param2";
    myCommand.Parameters.AddWithValue("@Param2", myParam2);
    using (SqlDataReader reader = myCommand.ExecuteReader())
    {
        if (reader.Read())
        {
            string businessName = reader.GetString(reader.GetOrdinal("BusinessName"));
            MessageBox.Show(businessName);
        }
        else
        {
            MessageBox.Show(string.Format("Sorry, no business found with id = {0}", myParam2));
        }
    }
}

Things to notice:

  • disposable resources are wrapped in using statements to ensure proper disposal even in case of exceptions
  • simplification of the parameter passed to the sql command
  • call the ExecuteReader on the command in order to retrieve an object allowing you to read the returned resultset.
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928