为什么我的查询在C#中没有正确执行?

时间:2016-11-02 02:21:21

标签: c# sql winforms

在MSSQL中写了这个查询:

SELECT Code, Description,LEAD(Code, 1) OVER (ORDER BY code) AS next_code FROM Liguanea_Lane WHERE code LIKE '%88%'

在我的C#代码中回写相同的查询,这次它接受来自组合框名称“search”的输入并在按钮单击上执行。如下所示:

  private void button1_Click(object sender, EventArgs e)
    {
        try
        {

            string connectionString = "Data Source=JAVY26;Initial Catalog=Pharmacies;Integrated Security=True";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string query = "SELECT Code, Description,LEAD(Code, 1) OVER (ORDER BY code) AS next_code FROM Liguanea_Lane WHERE code LIKE '%" + search.Text+"%'; ";
            SqlCommand cmd = new SqlCommand(query, con);

            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string scode = dr.GetString(dr.GetOrdinal("next_code"));
                textBox2.Text = scode;
            }
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
    }

我的问题是我不断得到:“数据是空的。无法在空值上调用此方法或属性。”我的代码中的查询错了吗?它在我的SQL Server中运行良好。

2 个答案:

答案 0 :(得分:0)

我认为问题是因为:

public class Location
{
    public int LocationId { get; set; }

    public int NextLocationId { get; set; }
    public int PreviousLocationId { get; set; }

    [ForeignKey("PreviousLocationId")]
    public Location PreviousLocation { get; set; }
    [ForeignKey("NextLocationId")]
    public Location NextLocation { get; set; }
}

这是一个没有用户干预的循环,假设查询返回3行:

while (dr.Read())
{
   string scode = dr.GetString(dr.GetOrdinal("next_code"));
   textBox2.Text = scode;
}

在循环的第一遍中,它将881分配给textbox2.Text; 在第二遍,它将882分配给textbox2.Text 在第三次传递时它出错,因为next_code为null。

答案 1 :(得分:0)

我是即兴创作的。我刚刚在现有数据库中添加了一个next_code字段,并根据前面和后面的内容复制值。刚刚完成了数据库中的所有工作并修改了代码:

private void button1_Click(object sender, EventArgs e)
    {
        try
        {

            string connectionString = "Data Source=JAVY26;Initial Catalog=Pharmacies;Integrated Security=True";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string query = "SELECT Code, Description, Next_Code FROM Liguanea_Lane WHERE code LIKE '%" + search.Text+"%'; ";
            SqlCommand cmd = new SqlCommand(query, con);

            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
               string scode = dr.GetString(dr.GetOrdinal("next_code"));
                textBox2.Text = scode;

            }
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
    }

现在返回我需要的值。感谢大家的反馈。感谢您尝试和协助的时间。