Search code examples
c#asp.netsql-server

How to read each row and value with SqlCommand in C#?


I'm new to using C# and am now messing around with SQL Server connections. My connection is working and I can run queries, I just can't view any of the data that is returned. I've seen that you need to run command.ExecuteReader() to get the data back but I cannot get any other data than the first column and row.

Here is my code:

<%@ WebHandler Language="C#" Class="biquery_query" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class biquery_query : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        var query = context.Request.QueryString["query"];
        query = "SELECT * FROM [hidden].[dbo].[hidden]";

        SqlConnection sqlConnection = new SqlConnection(@"Data Source=hidden;Initial Catalog=hidden;User ID=hidden;Password=hidden;");

        // Create Query Command
        SqlCommand command = new SqlCommand();
        command.CommandType = CommandType.Text;
        command.CommandText = query;
        command.Connection = sqlConnection;

        // Open connection and execute query
        sqlConnection.Open();
        command.ExecuteNonQuery();

        using(SqlDataReader rdr = command.ExecuteReader())
        {
            while(rdr.Read())
            {
                string app_id= rdr["app_id"].ToString();
                string app_os= rdr["app_os"].ToString();
                string date= rdr["date"].ToString();
                context.Response.Write(app_id);
            } 
        }

        sqlConnection.Close();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

My database table has 5 columns (app_id, app_os, date, unix, users).

Is there a way I can select rdr["app_id"][0] to get the first app_id or rdr["users"][30].

Any help would be greatly appreciated, thanks!


Solution

  • ExecuteNonQuery is used when the query is not going to return a resultset (like INSERT, or UPDATE).

    Remove the call to ExecuteNonQuery and just use ExecuteReader.