Display SQL query result in a label in asp.net

2020-03-26 04:12发布

问题:

I'm trying to display the SQL query result in a label but it's not showing. This is my code:

     string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
     SqlCommand showresult = new SqlCommand(result, conn);
     conn.Open();
     showresult.ExecuteNonQuery();
     string actresult = ((string)showresult.ExecuteScalar());
     ResultLabel.Text = actresult;
     conn.Close();

Need help please. Thanks!

回答1:

Try this one.

   string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
   SqlCommand showresult = new SqlCommand(result, conn);
   conn.Open();
   ResultLabel.Text = showresult.ExecuteScalar().ToString();
   conn.Close();


回答2:

Is there a typo in there? You have two calls to the database:

showresult.ExecuteNonQuery();

This won't return a value and I'm not sure why you would have it there

string actresult = ((string)shresult.ExecuteScalar());

Unless you have a shresult variable, this query should error. What is the shresult variable?



回答3:

Use SqlParameter to filter the result and call ExecuteScalar() or ExecuteReader() method.

 string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=@ID";
 SqlCommand showresult = new SqlCommand(result, conn);
 // If ID is int type
 showresult.Parameters.Add("@ID",SqlDbType.Int).Value=ID.Txt; 

 // If ID is Varchar then 
 //showresult.Parameters.Add("@ID",SqlDbType.VarChar,10).Value=ID.Txt; 

  conn.Open();
  string actresult = (string)showresult.ExecuteScalar(); 
  conn.Close();
  if(!string.IsNullOrEmpty(actresult))
       ResultLabel.Text = actresult;
  else
       ResultLabel.Text="Not found";


回答4:

using (SqlConnection conn = new SqlConnection(connectionString))
{
    string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = @id";
    SqlCommand showresult = new SqlCommand(result, conn);
    showresult.Parameters.AddWithValue("id", ID.Text);

    conn.Open();
    ResultLabel.Text = showresult.ExecuteScalar().ToString();
    conn.Close();
}

This will dispose the connection and has no string concatenation in the query.



回答5:

 conn.Open(); 
 string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
 SqlCommand showresult = new SqlCommand(result, conn);

 showresult.ExecuteNonQuery();
 int actresult = ((int)showresult.ExecuteScalar());
 ResultLabel.Text = actresult.Tostring();
 conn.Close();