Display SQL query result in a label in asp.net

2020-03-26 04:09发布

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!

5条回答
SAY GOODBYE
2楼-- · 2020-03-26 04:10
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.

查看更多
做自己的国王
3楼-- · 2020-03-26 04:17

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?

查看更多
Explosion°爆炸
4楼-- · 2020-03-26 04:21

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";
查看更多
Melony?
5楼-- · 2020-03-26 04:28

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();
查看更多
时光不老,我们不散
6楼-- · 2020-03-26 04:35
 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();
查看更多
登录 后发表回答