0

I have an SQLite table that I want to get multiple columns at once. I use a query similar to this to this one to get the data from the table: "SELECT LastName, FirstName, Age, Birthday FROM table1 ORDER BY LastName" I would assume that this gets all of the relevant data from the table but I don't know how to properly extract all of it from the query in C#. I use

SQLiteDataReader sqldr;
while (sqldr.Read())
{
 Console.WriteLine(sqldr.GetString(0));
}

to print out the data but this only prints out the data from the LastName column. How would I go about printing out the rest of the data from the query? I tried incrementing the value inside of GetString(); but that resulted in a System.IndexOutOfRangeException in System.Data.SQLite.dll

Any suggestions would be greatly appreciated. Thanks!

jazb
5,8476 gold badges40 silver badges44 bronze badges
asked Mar 30, 2022 at 3:48
3
  • Does this answer your question? How to use SqlDataReader to retrieve information from database, c# Commented Mar 30, 2022 at 4:37
  • @Jazb This doesn't seem to be entirely the same thing unless I am misreading it. They are only retrieving one column it seems. I am trying to retrieve data from multiple columns for multiple rows, one row at a time. Commented Mar 30, 2022 at 6:29
  • @Jazb After getting some sleep and coming back to this, I realized this was indeed what I was looking for. I'll write the answer out to this question at some point to make it a little more specific for anyone who happens to stumble across this question because it wasn't immediately obvious to me what the answer was when looking at that question. Thanks! Commented Mar 30, 2022 at 17:35

1 Answer 1

0

This should work:

using System.Data.SQLite;
string cs = @"URI=file:C:\Path\To\test.db";
using var con = new SQLiteConnection(cs);
con.Open();
string stm = "SELECT LastName, FirstName, Age, Birthday FROM table1 ORDER BY LastName";
using var cmd = new SQLiteCommand(stm, con);
using SQLiteDataReader sqldr = cmd.ExecuteReader();
while (sqldr.Read())
{
 Console.WriteLine($"{sqldr.GetString(0)} {sqldr.GetString(1)} {sqldr.GetInt32(2)}"); 
 //This covers LastName, FirstName, and Age. Add more fields as desired
}

The code above assumes that "Age" is saved as an integer in your SQLIte database.

answered Apr 3, 2022 at 13:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.