在asp.net中的标签中显示SQL查询结果

本文关键字:SQL 查询 结果 显示 asp net 标签 | 更新日期: 2023-09-27 18:20:08

我试图在标签中显示SQL查询结果,但没有显示。这是我的代码:

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

需要帮助。谢谢

在asp.net中的标签中显示SQL查询结果

试试这个。

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

里面有打字错误吗?您有两个对数据库的调用:

showresult.ExecuteNonQuery();

这不会返回值,我不知道你为什么会在那里

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

除非您有shresult变量,否则此查询应该会出错。shresult变量是什么?

使用SqlParameter过滤结果并调用ExecuteScalar()ExecuteReader()方法。

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

这将处理连接,并且在查询中没有字符串串联。

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