如何从SqlDataReader返回单个值?

时间:2012-01-02 15:12:48

标签: c# asp.net .net

我忘了在单层应用程序中返回值。

public  int Studentid()
    {
        try
        {
            SqlConnection con = new SqlConnection(connectionStr);
            SqlCommand cmd = new SqlCommand("SELECT s_id FROM student where name = + ('" + Request.QueryString.ToString() + "')", con);
            con.Open();
            SqlDataReader dr = null;
            con.Open();
            dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                //Want help hear how I return value
            }

            con.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

7 个答案:

答案 0 :(得分:21)

以下是您的方法的一个版本,可以实现您的目标。

public int GetStudentId()
{
    var sql = string.Format("SELECT s_id FROM student where name = '{0}'", Request.QueryString);
    using (var con = new SqlConnection(connectionStr))
    using (var cmd = new SqlCommand(sql, con))
    {
        con.Open();
        var dr = cmd.ExecuteReader();
        return dr.Read() ? return dr.GetInt32(0) : -1;
    }
}

除了重新抛出之外没有对异常执行任何操作时不需要使用try / catch(事实上,使用throw ex;而不是throw;丢失了原始堆栈跟踪此外,C#using语句负责以更少的代码行为您清理资源。

<强> 重要

将查询字符串直接传递给SQL,这意味着任何人都可以在数据库中执行随机SQL,可能会删除所有内容(或更糟)。阅读SQL Injection

答案 1 :(得分:4)

您应该使用using块,以确保正确关闭连接,命令和阅读器。然后你可以从if语句中返回值,并且在关闭对象之前不必将它存储在变量中。

您只需要打开一次连接。

您应该使用参数化查询,而不是将值连接到查询中。

public  int Studentid() {
  try {
    using (SqlConnection con = new SqlConnection(connectionStr)) {
      using (SqlCommand cmd = new SqlCommand("SELECT s_id FROM student where name = @Name", con)) {
        cmd.Parameters.Add("@Name", DbType.VarChar, 50).Value = Request.QueryString.ToString();
        con.Open();
        using (SqlDataReader dr = cmd.ExecuteReader()) {
          if (dr.Read()) {
            return dr.GetInt32(0);
          } else {
            return -1; // some value to indicate a missing record
            // or throw an exception
          }
        }
      }
    }
  } catch (Exception ex) {
    throw; // just as this, to rethrow with the stack trace intact
  }
}

答案 2 :(得分:2)

试试这个:

int s_id = (int) dr["s_id"];

答案 3 :(得分:1)

int studId=0;
if(rdr.Read())
{
  studId=rdr.GetInt32(rdr.GetOrdinal("s_id"));
}

答案 4 :(得分:1)

返回单个值的最简单方法是调用ExecuteScalar。您还应该修复SQL注入错误。你的意思是编码整个查询字符串数组,还是只挑选一个值?

public int StudentId()
{
    string sql = "SELECT s_id FROM student WHERE name = @name";
    using (var con = new SqlConnection(connectionStr))
    {
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.Add("@name", DbType.VarChar, 256).Value = Request.QueryString["name"];
            con.Open();
            return (int)cmd.ExecuteScalar();
        }
    }
}

答案 5 :(得分:0)

 if (dr.Read())
            {
                //Want help hear how i return value
                int value = dr.GetInt32("s_id");
            }

答案 6 :(得分:-1)

喜欢这个吗?

public  int Studentid()
{
        int studentId = -1;
        SqlConnection con = null;
        try
        {
            con = new SqlConnection(connectionStr);
            SqlCommand cmd = new SqlCommand("SELECT s_id FROM student where name = + ('" + Request.QueryString.ToString() + "')", con);
            SqlDataReader dr = null;
            con.Open();
            dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                studentId = dr.GetInt32(0);
            }

            dr.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if(con != null)
                 con.Close();
            con = null;
        }

       return studentId;
 }