我有下一个方法:

    private bool bla()
{

    int Minbuy, ordersTillNow;
    {
        SqlConnection connection = new SqlConnection("Data Source=****;Initial Catalog=****;User ID=****;Password=****;Integrated Security=False;");
        string commandtext = "SELECT Minbuy FROM items WHERE main = 1";
        string commandtext2 = "SELECT ordersTillNow FROM items WHERE main = 1";

        SqlCommand command = new SqlCommand(commandtext, connection);
        SqlCommand command2 = new SqlCommand(commandtext2, connection);

        connection.Open();

        Minbuy = (int)command.ExecuteScalar();
        ordersTillNow = (int)command2.ExecuteScalar();

        if (Minbuy < ordersTillNow)
            return true;
        else
            return false;

    }



}


并在page_上使用该方法加载:

        if (bla())
    {
        Image_V.Visible = true;
    }
    else
    {
       Image_X.Visible = true;
    }


SQL中查询结果的值是:


  MinBuy = 5
  
  ordersTillNow = 1


奇怪的是-没关系注意数据库中的值是什么(我将值更改为:MinBuy = 1,ordersTillNow = 8)-它显示image_v。 (在aspx页上-两个图像可见值都设置为false)。

代码有什么问题?

表设计:

表格名称:项目

列:itemId(int),main(bit),MinBuy(int),ordersTillNow(int)。

最佳答案

我认为可能是问题所在,上述SQL的结果可能返回多于1行。因此,它将给出错误的结果。

尝试将代码更改为:

string commandtext = "SELECT TOP 1 Minbuy FROM items WHERE main = 1";
string commandtext2 = "SELECT TOP 1 ordersTillNow FROM items WHERE main = 1";


您可以使用一个选择来代替2个选择

string queryString = "SELECT Minbuy, ordersTillsNow FROM items WHERE main = 1";
using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        connection.Open();

        SqlCommand command = new SqlCommand(queryString, connection);
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            MinBuy = int.Parse(reader[0].ToString());
            ordersTillsNow = int.Parse(reader[1].ToString());
            //Console.WriteLine(String.Format("{0}", reader[0]));
        }
    }

09-28 06:52