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!
-
Does this answer your question? How to use SqlDataReader to retrieve information from database, c#jazb– jazb2022年03月30日 04:37:57 +00:00Commented 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.1Poseidon3– 1Poseidon32022年03月30日 06:29:17 +00:00Commented 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!1Poseidon3– 1Poseidon32022年03月30日 17:35:57 +00:00Commented Mar 30, 2022 at 17:35
1 Answer 1
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.