- How can I return a single value from an SqlDataReader?
- 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 herr how i return value
- }
- con.Close();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- 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;
- }
- }
- int s_id = (int) dr["s_id"];
- int studId=0;
- if(rdr.Read())
- {
- studId=rdr.GetInt32(rdr.GetOrdinal("s_id"));
- }
- 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())
- {
- return dr.GetInt32(0);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if(con != null)
- con.Close();
- con = null;
- }
- }
- if (dr.Read())
- {
- //Want help hear how i return value
- int value = dr.GetInt32("s_id");
- }
- 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
- }
- }
- 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();
- }
- }
- }