Bind Results in C# using SQL prepared statements

筅森魡賤 提交于 2019-12-08 18:44:26

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!