• Stars
    star
    109
  • Rank 319,077 (Top 7 %)
  • Language
    C#
  • License
    Other
  • Created about 14 years ago
  • Updated about 8 years ago

Reviews

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

Repository Details

sqlite-net

sqlite-net is an open source, minimal library to allow .NET and Mono applications to store data in [http://www.sqlite.org SQLite 3 databases]. It is written in C# and is meant to be simply compiled in with your projects. It was first designed to work with MonoTouch on the iPhone, but has grown up to work on all the platforms (Mono for Android, .NET, Silverlight, WP7, WinRT, 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 with MonoTouch projects.

  • Thin wrapper over SQLite and should be fast and efficient. (The 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.)

  • 0 dependencies aside from a compiled form of the sqlite2 library.

Non-goals include:

Meta

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; }
	[MaxLength(8)]
	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 reponsiveness.

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:

var db = new SQLiteConnection("foofoo");
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 s = db.Insert(new Stock() {
		Symbol = symbol
	});
	Console.WriteLine("{0} == {1}", s.Symbol, s.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 conn = new SQLiteConnection("foofoo");
	var query = conn.Table<Stock>().Where(v => v.Symbol.StartsWith("A"));

	foreach (var stock in query)
		Debug.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:

var conn = new SQLiteAsyncConnection("foofoo");
conn.CreateTableAsync<Stock>().ContinueWith((results) =>
{
	Debug.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:

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

	var conn = new SQLiteAsyncConnection("foofoo");
	conn.InsertAsync(stock).ContinueWith((t) =>
	{
		Debug.WriteLine("New customer 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 predictates 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 conn = new SQLiteAsyncConnection("foofoo");
	var query = conn.Table<Stock>().Where(v => v.Symbol.StartsWith("A"));
		
	query.ToListAsync().ContinueWith((t) =>
	{
		foreach (var stock in t.Result)
			Debug.WriteLine("Stock: " + stock.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 conn = new SQLiteAsyncConnection("foofoo");
	conn.ExecuteScalarAsync<int>("select count(*) from Stock", null).ContinueWith((t) =>
	{
		Debug.WriteLine(string.Format("Found '{0}' stock items.", t.Result));
	});

Special note on use within Windows Store Apps (Windows 8/WinRT)

sqlite-net is fully compliant with WinRT Metro-style apps and will pass Microsoft Store validation.

Please note:

  • Database files will always be created in the path returned by Windows.Storage.ApplicationData.Current.LocalFolder.Path.

  • You will need a copy of sqlite3.dll for your app as well. You can get this from sqlite.org with an installer to the SQLite for Windows Runtime SDK.

More Repositories

1

AndroidAsync

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.
Java
7,439
star
2

ion

Android Asynchronous Networking and Image Loading
Java
6,299
star
3

scrypted

Scrypted is a high performance home video integration and automation platform
TypeScript
3,676
star
4

UniversalAdbDriver

One size fits all Windows Drivers for Android Debug Bridge.
C#
1,961
star
5

Superuser

C
1,421
star
6

vysor.io

Vysor - Mirror and Control your Phone
HTML
1,393
star
7

electron-chrome

JavaScript
971
star
8

UrlImageViewHelper

Android library that sets an ImageView's contents from a url. Manages image downloading, caching, and makes your coffee too.
Java
970
star
9

support-wiki

385
star
10

AnyKernel

AnyKernel is a template for an update.zip that can apply any kernel to any ROM, regardless of ramdisk.
Shell
190
star
11

Widgets

UI widgets I use across my apps.
Java
173
star
12

androidmono

The Mono project ported to Android
C#
148
star
13

EFI-X99

Hackintosh Guide: Gigabyte X99P-SLI, Intel 6950X, Radeon
Rich Text Format
124
star
14

ROMManagerManifest

JavaScript
121
star
15

boilerplate

Java
97
star
16

quickjs

QuickJS Fork with VSCode debugging support
C
81
star
17

PushSms

Java
80
star
18

android-support-v7-appcompat

61
star
19

quack

JavaScript
57
star
20

Loggy

JavaScript
54
star
21

android_system_core

Android System Core (CM)
C
42
star
22

EFI-SkullCanyon

Shell
35
star
23

AppleMobileDeviceSupport

25
star
24

AndroidNetworkBench

Java
23
star
25

MediaRouterSample

Java
22
star
26

Clear

Java
22
star
27

mvn-repo

20
star
28

scrypted.app

HTML
18
star
29

android_vendor_motorola_sholes

Shell
17
star
30

android_device_motorola_sholes

Shell
17
star
31

DroidXBootstrap

Java
17
star
32

csharp-sqlite

C#
15
star
33

koush.com

SCSS
15
star
34

logpush

JavaScript
14
star
35

Chromecast

Java
14
star
36

android_bionic

Android Bionic Library (cyanogenmod)
C
13
star
37

babel

Java
13
star
38

GrowBox

Java
12
star
39

android_device_htc_inc

C
12
star
40

nothingtoseeheremovealong

Shell
11
star
41

CastResources

11
star
42

CastAPI

Java
11
star
43

vysor-cli

TypeScript
10
star
44

fascinate_initramfs

Shell
10
star
45

CarbonResources

10
star
46

android_vendor_motorola_droidx

C
9
star
47

WindowlessControls

A Windows Mobile UI Framework that allows for quick and easy creation of controls and user interfaces that can target any screen resolution and device type.
C#
9
star
48

android_vendor_samsung_galaxys

Shell
8
star
49

legacy_vendor_koush

Shell
8
star
50

CastSite

JavaScript
8
star
51

adb.clockworkmod.com

CSS
8
star
52

GithubProjects

Embed this script into a webpage to get a real time view of your Github repositories!
JavaScript
8
star
53

release

7
star
54

GoogleVoiceService

Java
7
star
55

Droid2Bootstrap

7
star
56

galaxy-initramfs

7
star
57

android_vendor_htc_inc

Shell
7
star
58

android_device_samsung_epic4g

C
7
star
59

dblinq

C#
7
star
60

dev.vysor.io

CSS
6
star
61

WindowlessControlsTutorial

C#
6
star
62

inkwire.io

JavaScript
6
star
63

Screenshot

Java
6
star
64

android-support

6
star
65

scrypted-unifi-protect

TypeScript
6
star
66

google-play-services_lib

Java
6
star
67

epic4gtouch_initramfs_files

Rust
6
star
68

scratch

Kotlin
6
star
69

TiledMaps

A .NET client for tile servers such as Google Maps and Virtual Earth.
C#
6
star
70

AMD7000Controller.kext

5
star
71

scrypted-vscode-typescript

TypeScript
5
star
72

GoogleVoice

C#
5
star
73

WhilWheatonPermissionFixer

Java
5
star
74

Kexts

5
star
75

dropbox-sdk

Java
5
star
76

OpenGLES

A .NET wrapper for OpenGL ES.
C#
5
star
77

Xaml

C#
4
star
78

AsyncTask

C#
4
star
79

TetherResources

4
star
80

otaxdelta3

C
4
star
81

EFI

My EFI partition my hackintosh
JavaScript
4
star
82

sapphire-open

Build configuration and makefiles that can be used to build Android images for the MyTouch.
Shell
4
star
83

clockworkmod.com

CSS
4
star
84

android_vendor_htc_magic

Build configuration and makefiles that can be used to build Android images for the Magic.
Shell
4
star
85

jenkinsmanifest

CSS
4
star
86

android_vendor_htc_supersonic

Shell
4
star
87

android_external_yaffs2

C
4
star
88

ClockworkModLauncher

Java
4
star
89

TiledMapsTest

C#
4
star
90

SyntaxHighlighter

SyntaxHighlighter fork on git
JavaScript
3
star
91

proprietary_vendor_nvidia

3
star
92

Chips

3
star
93

scrypted-google-home

TypeScript
3
star
94

proprietary_vendor_google

JavaScript
3
star
95

GoogleVoiceRepo

3
star
96

scrypted-sdk

JavaScript
3
star
97

android_device_endeavoru

3
star
98

android_vendor_samsung_fascinate

Shell
3
star
99

scrypted-homekit

TypeScript
3
star
100

InkwireResources

3
star