使用SQL预处理语句将结果绑定到C#中

时间:2012-02-11 15:10:31

标签: c# sql prepared-statement

使用此:

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?

如何将预准备语句的结果绑定到变量,以便我可以操作它们?

1 个答案:

答案 0 :(得分:6)

试试这样:

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));
        }
    }
}

需要注意的事项:

  • 一次性资源包含在使用陈述中,以确保即使在例外的情况下也能正确处理
  • 简化传递给sql命令的参数
  • 调用命令上的ExecuteReader以检索允许您读取返回结果集的对象。