• Stars
    star
    3,753
  • Rank 11,749 (Top 0.3 %)
  • Language
    C#
  • License
    MIT License
  • Created over 13 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple, powerful, cross-platform SQLite client and ORM for .NET

SQLite-net

[GitHub Action] [Code Coverage Report]

Use one of these packages:

Version Package Description
NuGet Package sqlite-net-pcl .NET Standard Library
NuGet Package with Encryption sqlite-net-sqlcipher With Encryption Support
NuGet Package using P/Invoke sqlite-net-static Special version that uses P/Invokes to platform-provided sqlite3
NuGet Package without a SQLitePCLRaw bundle sqlite-net-base wothout a SQLitePCLRaw bundle so you can choose your own provider

SQLite-net is an open source, minimal library to allow .NET, .NET Core, and Mono applications to store data in SQLite 3 databases. It was first designed to work with Xamarin.iOS, but has since grown up to work on all the platforms (Xamarin.*, .NET, UWP, Azure, etc.).

SQLite-net was designed as a quick and convenient database layer. Its design follows from these goals:

  • Very easy to integrate with existing projects and runs on all the .NET platforms.

  • Thin wrapper over SQLite that is fast and efficient. (This library should not be the performance bottleneck of your queries.)

  • Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.

  • Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)

NuGet Installation

Install sqlite-net-pcl from NuGet.

Important: You will need to add the NuGet package to both your .NET Standard library project and your platform-dependent app project.

Source Installation

SQLite-net is all contained in 1 file (I know, so cool right?) and is easy to add to your project. Just add SQLite.cs to your project, and you're ready to start creating tables. An asynchronous implementation can be found in SQLiteAsync.cs.

Please Contribute!

This is an open source project that welcomes contributions/suggestions/bug reports from those who use it. If you have any ideas on how to improve the library, please post an issue here on GitHub. Please check out the How to Contribute.

Example Time!

Please consult the Wiki for, ahem, complete documentation.

The library contains simple attributes that you can use to control the construction of tables. In a simple stock program, you might use:

public class Stock
{
	[PrimaryKey, AutoIncrement]
	public int Id { get; set; }
	public string Symbol { get; set; }
}

public class Valuation
{
	[PrimaryKey, AutoIncrement]
	public int Id { get; set; }
	[Indexed]
	public int StockId { get; set; }
	public DateTime Time { get; set; }
	public decimal Price { get; set; }
}

Once you've defined the objects in your model you have a choice of APIs. You can use the "synchronous API" where calls block one at a time, or you can use the "asynchronous API" where calls do not block. You may care to use the asynchronous API for mobile applications in order to increase responsiveness.

Both APIs are explained in the two sections below.

Synchronous API

Once you have defined your entity, you can automatically generate tables in your database by calling CreateTable:

// Get an absolute path to the database file
var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyData.db");

var db = new SQLiteConnection(databasePath);
db.CreateTable<Stock>();
db.CreateTable<Valuation>();

You can insert rows in the database using Insert. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:

public static void AddStock(SQLiteConnection db, string symbol) {
	var stock = new Stock() {
		Symbol = symbol
	};
	db.Insert(stock);
	Console.WriteLine("{0} == {1}", stock.Symbol, stock.Id);
}

Similar methods exist for Update and Delete.

The most straightforward way to query for data is using the Table method. This can take predicates for constraining via WHERE clauses and/or adding ORDER BY clauses:

var query = db.Table<Stock>().Where(v => v.Symbol.StartsWith("A"));

foreach (var stock in query)
	Console.WriteLine("Stock: " + stock.Symbol);

You can also query the database at a low-level using the Query method:

public static IEnumerable<Valuation> QueryValuations (SQLiteConnection db, Stock stock) {
	return db.Query<Valuation> ("select * from Valuation where StockId = ?", stock.Id);
}

The generic parameter to the Query method specifies the type of object to create for each row. It can be one of your table classes, or any other class whose public properties match the column returned by the query. For instance, we could rewrite the above query as:

public class Val
{
	public decimal Money { get; set; }
	public DateTime Date { get; set; }
}

public static IEnumerable<Val> QueryVals (SQLiteConnection db, Stock stock) {
	return db.Query<Val> ("select \"Price\" as \"Money\", \"Time\" as \"Date\" from Valuation where StockId = ?", stock.Id);
}

You can perform low-level updates of the database using the Execute method.

Asynchronous API

The asynchronous library uses the Task Parallel Library (TPL). As such, normal use of Task objects, and the async and await keywords will work for you.

Once you have defined your entity, you can automatically generate tables by calling CreateTableAsync:

// Get an absolute path to the database file
var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyData.db");

var db = new SQLiteAsyncConnection(databasePath);

await db.CreateTableAsync<Stock>();

Console.WriteLine("Table created!");

You can insert rows in the database using Insert. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:

var stock = new Stock()
{
	Symbol = "AAPL"
};

await db.InsertAsync(stock);

Console.WriteLine("Auto stock id: {0}", stock.Id);

Similar methods exist for UpdateAsync and DeleteAsync.

Querying for data is most straightforwardly done using the Table method. This will return an AsyncTableQuery instance back, whereupon you can add predicates for constraining via WHERE clauses and/or adding ORDER BY. The database is not physically touched until one of the special retrieval methods - ToListAsync, FirstAsync, or FirstOrDefaultAsync - is called.

var query = db.Table<Stock>().Where(s => s.Symbol.StartsWith("A"));

var result = await query.ToListAsync();

foreach (var s in result)
	Console.WriteLine("Stock: " + s.Symbol);

There are a number of low-level methods available. You can also query the database directly via the QueryAsync method. Over and above the change operations provided by InsertAsync etc you can issue ExecuteAsync methods to change sets of data directly within the database.

Another helpful method is ExecuteScalarAsync. This allows you to return a scalar value from the database easily:

var count = await db.ExecuteScalarAsync<int>("select count(*) from Stock");

Console.WriteLine(string.Format("Found '{0}' stock items.", count));

Manual SQL

sqlite-net is normally used as a light ORM (object-relational-mapper) using the methods CreateTable and Table. However, you can also use it as a convenient way to manually execute queries.

Here is an example of creating a table, inserting into it (with a parameterized command), and querying it without using ORM features.

db.Execute ("create table Stock(Symbol varchar(100) not null)");
db.Execute ("insert into Stock(Symbol) values (?)", "MSFT");
var stocks = db.Query<Stock> ("select * from Stock");

Using SQLCipher

You can use an encrypted database by using the sqlite-net-sqlcipher NuGet package.

The database key is set in the SqliteConnectionString passed to the connection constructor:

var options = new SQLiteConnectionString(databasePath, true,
	key: "password");
var encryptedDb = new SQLiteAsyncConnection(options);

If you need set pragmas to control the encryption, actions can be passed to the connection string:

var options2 = new SQLiteConnectionString (databasePath, true,
	key: "password",
	preKeyAction: db => db.Execute("PRAGMA cipher_default_use_hmac = OFF;"),
	postKeyAction: db => db.Execute ("PRAGMA kdf_iter = 128000;"));
var encryptedDb2 = new SQLiteAsyncConnection (options2);

Thank you!

Thank you to the .NET community for embracing this project, and thank you to all the contributors who have helped to make this great.

Thanks also to Tirza van Dijk (@tirzavdijk) for the great logo!

More Repositories

1

Ooui

A small cross-platform UI library that brings the simplicity of native UI development to the web
C#
1,616
star
2

Netjs

Compile .NET assemblies to TypeScript and JavaScript
C#
955
star
3

NGraphics

NGraphics is a cross platform library for rendering vector graphics on .NET. It provides a unified API for both immediate and retained mode graphics using high quality native renderers.
C#
696
star
4

FuGetGallery

An alternative web UI for browsing nuget packages
C#
672
star
5

webgpu-torch

Tensor computation with WebGPU acceleration
TypeScript
488
star
6

Continuous

Continuous IDE Addin enables live coding from Xamarin Studio and Visual Studio
C#
268
star
7

CLanguage

C parser, compiler, and interpreter for .NET
C#
252
star
8

Bind

A small but powerful C# library for data binding
C#
205
star
9

CrossGraphics

Cross-platform Graphics Library for .NET
C#
194
star
10

transformers-js

Browser-compatible JS library for running language models
JavaScript
178
star
11

ImmutableUI

Immutable objects that mirror popular object oriented UIs
C#
115
star
12

ListDiff

C#
113
star
13

Iril

Compiles LLVM IR (bytecode) or C to .NET Assemblies
LLVM
94
star
14

web-transformers

Transformer neural networks in the browser
TypeScript
89
star
15

Praeclarum.MacCatalyst

Convert your Xamarin.iOS apps to Mac Catalyst apps by adding this nuget.
C#
63
star
16

Csg

Solid modeling library for .NET
C#
62
star
17

AskGPT

Ask ChatGPT questions from the command line.
C#
58
star
18

SwiftSharp

Swift compiler for .NET
HTML
52
star
19

Gone

GO compiler for .NET
F#
42
star
20

HotDogOrNot

A minimal Xamarin CoreML app to detect hotdogs
C#
40
star
21

lcars

LCARS Reader - the coolest iPad news reader not on the App Store
C#
36
star
22

CSharpInteractive

C# Interactive is a REPL for C# in Xamarin Studio
C#
30
star
23

Praeclarum

My general purpose library
C#
29
star
24

QuickTest

C#
28
star
25

GooglePlus

GooglePlus API Documentation and .NET Implementation
C#
27
star
26

MetalTensors

.NET Neural Network training library using Apple's Metal Performance Shaders
C#
26
star
27

runcs

The C# compiler hosted in a web app
C#
26
star
28

odata

OData Browser for the iPhone
C#
26
star
29

CSharpToSwift

Converts your C# projects to Swift
C#
23
star
30

StopCrashing

Script to detect possible sources of crashes in Xamarin apps
F#
21
star
31

FunctionalMeetup

Example code for Frank Krueger's Functional Mobile Apps talk at NDC Oslo 2016
F#
19
star
32

EasyLayout

EasyLayout makes writing auto layout code in Xamarin.iOS easier.
C#
18
star
33

SdfKit

.NET library to convert signed distance functions (SDFs) into triangle meshes and 3D renders
C#
17
star
34

OouiChat

Chat room web app built using Xamarin.Forms, ASP.NET, and Ooui
C#
16
star
35

MarriageClock

An IoT thing in the shape of heart that tells you how long you've been married
C++
13
star
36

ThreeDO

C#
13
star
37

Ur

Game of Ur using Blazor
C#
13
star
38

CircuitTranslations

Language support for iCircuit
F#
13
star
39

ARDemo

Xamarin Evolve 2014 Augmented Reality Demo
C#
12
star
40

fuget

C#
10
star
41

praeclarum.github.io

Frank A. Krueger's blog
HTML
10
star
42

caulker

3D Map for MonoTouch
C#
10
star
43

WebGlobe

3D Globe Screensaver Written in WebGPU
JavaScript
9
star
44

JavaScriptLanguage

Resharper add-in that decompiles to JavaScript.
C#
8
star
45

NMusic

Library and demo app for composing music and playing it on iOS
C#
8
star
46

Demo11

iOS 11 Demo Code Presented at the Seattle Mobile .NET Meetup
C#
8
star
47

BuildLight

Show IDE build status using an IoT device
C#
8
star
48

circuitpython-net

CircuitPython compiled to run on .NET
C#
8
star
49

CuneiformTranslators

Neural network trained to translate from ancient languages to modern languages
Jupyter Notebook
8
star
50

ukf

Unscented Kalman Filter Library
7
star
51

ClrTools

Tools for .NET Developers
C#
7
star
52

ImageRecognizer

Uses Metal Performance Shaders on iOS 13+ to train a neural network to recognize shapes
C#
7
star
53

rt

My Pet Raytracer in C#
C#
6
star
54

Monospace11

Demo code from Frank Krueger's talk at Monospace
C#
6
star
55

rouse

Declarative RESTful server
C#
5
star
56

NEcho

Amazon Echo ("Alexa") ASP.NET Core Web Service
C#
5
star
57

html5

C#
5
star
58

NeuralScanner

C++
4
star
59

Fom

F#
4
star
60

VectorPerf

Measures the performance of different vector types in .NET
C#
4
star
61

Knossus

Quick and easy web apps
C#
4
star
62

WasmAloneLab

HTML
4
star
63

UIDays

Cataloging the release dates of various UI frameworks
4
star
64

HomeAI

C#
4
star
65

ColmapSharp

COLMAP builds and bindings for .NET
C++
4
star
66

SubMark1Sim

F# Code to visualize a submarine control simulation
F#
3
star
67

AppleNative.Templates

F#
3
star
68

dotnet-tree-sitter

.NET bindings to the Tree-sitter parsing library
Makefile
3
star
69

Lilui

The lilest cross platform UI library for .NET
C#
3
star
70

BuildBoard

Display build status on an LED matrix
C++
2
star
71

nerf-py

Python
1
star
72

VacuumMold

C#
1
star
73

PythonRepl

Python REPL for iOS using Xamarin and IronPython
C#
1
star
74

BoxEditor

Generic box-based diagram editor for .NET
C#
1
star
75

Armina

Programming language cross compilation tools
C#
1
star