Skip to content

Instantly share code, notes, and snippets.

@orlodax
Created July 24, 2019 10:20
Show Gist options
  • Select an option

  • Save orlodax/4955f65a4f60a4b9d0a9f4241fdf8d5e to your computer and use it in GitHub Desktop.

Select an option

Save orlodax/4955f65a4f60a4b9d0a9f4241fdf8d5e to your computer and use it in GitHub Desktop.
Read SQLite table and store results inside DataTable C# UWP
DataTable ExecuteReadQuery(string query)
{
DataTable entries = new DataTable();
using (SqliteConnection db = new SqliteConnection(ConnectionString))
{
SqliteCommand selectCommand = new SqliteCommand(query, db);
try
{
db.Open();
SqliteDataReader reader = selectCommand.ExecuteReader();
if (reader.HasRows)
for (int i = 0; i < reader.FieldCount; i++)
entries.Columns.Add(new DataColumn(reader.GetName(i)));
int j = 0;
while (reader.Read())
{
DataRow row = entries.NewRow();
entries.Rows.Add(row);
for (int i = 0; i < reader.FieldCount; i++)
entries.Rows[j][i] = (reader.GetValue(i));
j++;
}
db.Close();
}
catch (SqliteException e)
{
OnSQLiteError(new SQLiteErrorEventArgs(e));
db.Close();
}
return entries;
}
}
@stefanvesely
Copy link

Hi, your code helped me a lot, I didn't know SQLite had a DataAdapter similar to normal SQL server so used your code a bunch, I even did a version that gets a schema cause your code doesnt get a schema.
Here is an updated version of your code using a DataAdapter.

Thanks Again!

public DataTable SQLiteDataTableWithQuery(string sQuery)
{
DataTable dtReturnTable = new DataTable();
sqlitecon.Open();
SQLiteCommand SQLiteCommand = new SQLiteCommand();
SQLiteCommand = sqlitecon.CreateCommand();
SQLiteCommand.CommandText = string.Format(sQuery);
SQLiteDataAdapter SQLITEDataAdapter = new SQLiteDataAdapter(SQLiteCommand);
SQLITEDataAdapter.Fill(dtReturnTable);
sqlitecon.Close();
return dtReturnTable;
}

@orlodax
Copy link
Author

orlodax commented Jul 2, 2022

Thank you @stefanvesely !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment