Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how do I use Console.WriteLine method to write ALL columns from my SqlCommand

I'm new to C# but have managed to piece together an SQLCommand query. However , I can't for the life of me figure out how to get it to display all columns. The below code is what i have currently (it successfully shows the first 5 columns):

Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3} \t| {4} \t",
    reader[0], reader[1], reader[2], reader[3], reader[4]));

What is the simplest way to show ALL columns without having to list each one like I did above? Also, is there a way to specifically name the columns that i want to display? for example, the below successfully shows the "company" column but I cant figure out how to do multiple columns specifically. What if i wanted to show "company" and "FiscalYear"?:

Console.WriteLine(reader["Company"].ToString());

I researched this for about 2 hours but was unable to come up with a solution. thank you very much for your help!

like image 900
Jar Avatar asked May 22 '26 05:05

Jar


2 Answers

You can use a StringBuilder to create the text in a loop

var sb = new StringBuilder();
for (int i = 0; i < reader.FieldCount; i++) {
    sb.Append($"{reader[i]} \t |");
}
sb.Length -= 4; // Remove the last " \t |".
Console.WriteLine(sb);

sb.Append(something) is more efficient than s = s + something, because string concatenations always create a new string object and copy the old string to the new one before appending something. Whereas the StringBuilder works with a buffer and can append several times until the buffer is full and must be resized.

The $ stands for string interpolation. These two lines are equivalent:

String.Format("{0}, {1}, {2}", a, b, c)
$"{a}, {b}, {c}"
like image 161
Olivier Jacot-Descombes Avatar answered May 23 '26 18:05

Olivier Jacot-Descombes


If your reader variable is an instance of SqlDataReader, you could do something like this:

void Main()
{
    SqlDataReader reader = getDataReader();   \\Code that returns a data reader
    Console.WriteLine(createOutputString(reader));
}

private string createOutputString(SqlDataReader reader)
{
    //Create an array to hold all the values of the reader
    object[] values = new object[reader.FieldCount];

    //Fill the array with the values
    reader.GetValues(values);

    //Return a string with each value of the array separated by a delimiter
    return string.Join(" \t | ", values);
}
like image 34
Chris Dunaway Avatar answered May 23 '26 19:05

Chris Dunaway