在查询中使用sqldatareader和where子句

时间:2016-09-09 08:38:16

标签: c# sql sql-server

我需要从表中读取一个特定值,才能在我的字段中使用它 但是当我在查询中插入where子句时,它只获取null值。

我的代码是:

string query_select_id = "SELECT * from table1 WHERE column1=@value";

SqlConnection con = new SqlConnection(ConString);
try
{
    con.Open();
    SqlCommand createCommand = new SqlCommand(query_select_id, con);
    createCommand .Parameters.Add("@value", SqlDbType.Int).Value  =Convert.ToInt32(textbox.Text);

    SqlDataReader dr = createCommand.ExecuteReader();
    while (dr.Read())
    {
        intvalue= dr.GetInt32(12); 
        // 12 is the index of a column in table of the value I wanna get
    }
    con.Close();

    textboxvalue.Text = intvalue.ToString();

}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

3 个答案:

答案 0 :(得分:0)

使用SELECT *代替SELECT column1dr.GetInt32(12)(结果中的值的常量索引)是非常糟糕的。试试SELECT column1 FROM table1 WHERE column1=@value并使用ExecuteScalar()获取唯一的结果,而不是SqlDataReaderwhile循环。

答案 1 :(得分:0)

如果只需要一个值,则应使用ExecuteScalar方法。我使用TOP 1和列名来确保select语句只返回一个值。

string query_select_id = "SELECT TOP 1 COLUMN12 from table1 WHERE column1=@value";
SqlConnection con = new SqlConnection(ConString);
int intvalue;
try
{
    con.Open();
    SqlCommand createCommand = new SqlCommand(query_select_id, con);
    createCommand.Parameters.Add("@value", SqlDbType.Int).Value  =Convert.ToInt32(textbox.Text);
    object result = cmd.ExecuteScalar();
    if(result == null)
    {
        textboxvalue.Text = "Result is NULL";
    }
    else
    {

        intvalue = (int) result; 
        textboxvalue.Text = intvalue.ToString();
    }
    con.Close();


}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

答案 2 :(得分:0)

试试这个:

createCommand.Parameters.Add更改为createCommand.Parameters.AddWithValue

    string query_select_id = "SELECT * from table1 WHERE column1=@value";

    SqlConnection con = new SqlConnection(ConString);

    try
    {
        con.Open();
        SqlCommand createCommand = new SqlCommand(query_select_id, con);
        //createCommand .Parameters.AddWithValue("@value", SqlDbType.Int).Value=Convert.ToInt32(textbox.Text);
        createCommand .Parameter.AddWitheValue("@value",textbox.Text);
        SqlDataReader dr = createCommand.ExecuteReader();
        while (dr.Read())
        {
            intvalue= dr.GetInt32(12); 
        // 12 is the index of a column in table of the value I wanna get

        }
        con.Close();

        textboxvalue.Text = intvalue.ToString();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }