2

I'd like to output a string (or possibly other variable type if string isn't ideal) based on the output of a SQLDataReader read. I have been playing around with the "while" loop, while (reader.Read())

I need to end up with something I can serialize with json.net.

Here's my current code - it outputs to debug log just to make sure I was successfully reading from the database.

protected void Page_Load(object sender, EventArgs e)
    {

        string connectionString = "Data Source =.\\SQLEXPRESS; Initial Catalog = TeamProject; Integrated Security = True; MultipleActiveResultSets = True";

        string querystring = "RosterMake";

        using (SqlConnection connection = 
            new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(querystring, connection);
            command.CommandType = CommandType.StoredProcedure;

            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    System.Diagnostics.Debug.WriteLine("\t{0}\t{1}\t{2}",
                    reader[0], reader[1], reader[2]);

                    //  What do I put here to make the results something I can 
                    //  serialize with json.net???

                }
                reader.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("oops");
            }
        }
    }
}

Thanks in advance!

5
  • and.. if you dont use sqldatareader, use SqlDataAdapter.Fill a DataTable, DataTable is easy to convert to xml Commented Jul 13, 2017 at 13:52
  • 2
    What has this question to do with SqlDataReader? Isn't it just about how to convert a string to a json object? You're showinjg a lot of code but actually you are asking for a json tutorial. Commented Jul 13, 2017 at 13:56
  • Newtonsoft.Json will help you, just need to create a class that represents needed JSON format, and then fill List<YourClass> with reader[i] values Commented Jul 13, 2017 at 13:56
  • 1
    @TimSchmelter The issue here is storing it somewhere i can access it with json.net. Unless you know of a way to pass the SQLDataReader straight to json... I just don't know what the best way to store it so I can serialize it later. Commented Jul 13, 2017 at 13:59
  • @KeltonCrouse: a SqlDataReader reads data which comes from a database and gives you an object. It has methods like reader.GetString(0) that gives you already the right type. But you have to process this string yourself, there is no automatism of the datareader. But haveyou tried this:JObject.Parse(reader.GetString(0))? Commented Jul 13, 2017 at 14:02

4 Answers 4

7

You could use a List<Dictionary<string, object>> to hold the values and serialize it. The Newtonsoft.Json will serialize it as a simple json. See the code as an example and the comments:

// define the list
var values = new List<Dictionary<string, object>>();
try
{
    connection.Open();
    // Use the using block to make sure you are disposing the dataReader object.
    using (SqlDataReader reader = command.ExecuteReader())
    {
        do
        {               
            while (reader.Read())
            {
                // define the dictionary
                var fieldValues = new Dictionary<string, object>();

                // fill up each column and values on the dictionary                 
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    fieldValues.Add(reader.GetName(i), reader[i]);
                }

                // add the dictionary on the values list
                values.Add(fieldValues);

            }
        } while (reader.NextResult());   // if you have multiple result sets on the Stored Procedure, use this. Otherwise you could remove the do/while loop and use just the while.
    }
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine("oops");
}

Now you can serialize the values using JsonConvert.Serialize(values) and you will get it as a json like this:

[
    {
        "Name": "John", Age: 30, Sex: "M"
    },
    {
        "Name": "Maria", Age: 28, Sex: "F"
    }
]
Sign up to request clarification or add additional context in comments.

5 Comments

how does this work if the shape of the recordsets are different, in the case of multiple-recordsets?
Because it can be deserialized to a List<Dictionary<string, object>>.
so you get two arrays?
A Dictionary is a key-pair value data structure. It will be deserializating a single object like { name: 'Charles', lastName: 'Okwuagwu }. string` is the proeprty name and object is the value. the value must be object beacuse it can be a string, number, etc.. Given you have a list on the json, then you define a List<Dictionary<string, object>> for many objects. That's why it works.
Thanks, I found an alternative. I use WriteStartArray(); and WriteEndArray(); to delimit each NextResult(); into separate arrays
6

It's simple to convert SqlDataReader to JSON. The thing to have is Newtonsoft.Json; Library Here is Example

            SqlDataReader rdr = cmd.ExecuteReader();
            //sqlDatoToJson(rdr);
            var datatable = new DataTable();
            datatable.Load(rdr);
            string JsonResponse = string.Empty;
            JsonResponse = JsonConvert.SerializeObject(datatable);
            System.Diagnostics.Debug.WriteLine("3");
            System.Diagnostics.Debug.WriteLine(rdr);
            con.Close();
            return new JsonResult() { Data = JsonResponse,JsonRequestBehavior = JsonRequestBehavior.AllowGet };

Comments

0

Just use the GetString() method on the SqlDataReader. You want something like this:

string myString;

using (SqlDataReader rdr = command.ExecuteReader())
{
    do
    {
        while (rdr.Read())
        {
            myString = rdr.GetString(0);
        }
    } while (rdr.NextResult());
}

Note this just blindly reads strings until there's nothing left. It's up to you to put the logic in correctly.

Comments

0

you can return a list:

 public List<EnEntity> methodname(string pParam1)
    {
        try
        {
            List<EnEntity> ListEntity = new List<EnEntity>();
            SqlCommand cmd = new SqlCommand("sp_name", conexion);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@vParam", SqlDbType.VarChar).Value = pParam1;

            SqlDataReader drd = cmd.ExecuteReader();

            if (drd.HasRows)//!=null
            {
                int pos_iIndex = drd.GetOrdinal("iColumnaName");
                while (drd.Read())
                {
                    EnEntity oEnEntity = new EnEntity();

                    oEnEntity.iPropertie = drd.IsDBNull(pos_iIndex) ? 0 : drd.GetInt32(pos_iIndex);

                    ListEnEntity.Add(oEnEntity);
                }
                drd.Close();

            }
            return (ListEnEntity);
        }
        catch (Exception ex)
        {                
            throw ex;
        }
    }

2 Comments

It will be better if all variables and methods will be named in English, otherwise they meaning is a mystery for those who do not understand worlds like : ListarReporteSegunPeriodoFecha
i did, i hope this help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.