Read more about C # Sqlite local storage

Source: Internet
Author: User
1. Download SQLite dll from:

Http://www.sqlite.org/download.html

Windows version:

Http://www.sqlite.org/2016/sqlite-dll-win32-x86-3130000.zip

2. Copy Sqlite3.dll to Bin directory

3. Install Nuget:install-package sqlite-net
SQLite.CS and SQLiteAsync.cs will be found in the project after installation
4. Demo Code:
4.1 Create an abstract base model:

Public abstract class Basemodel    {        [PrimaryKey] public        Guid Id {get; set;}        Protected Basemodel ()        {            Id = Guid.NewGuid ();        }    }

4.2 Test model

public class Book:basemodel    {public book        ()        {                    } public book        (string title, string author, int pages)            : Base ()        {            title = title;            Author = Author;            pages = pages;        }        public string Title {get; set;}        public int Pages {get; set;}        public string Author {get; set;}        public override string ToString ()        {            return string. Format ("ID: {0}, Title: {1}, Author: {2}, Pages: {3}", ID, title, Author, pages);        }    }

4.3 Creating a helper class

public class Sqlitehelper {Private Const string DBPath = "Book.db";        Private Const int operation_success = 1;            public static bool Trydroptable<t> () {using (var db = new Sqlite.sqliteconnection (DBPath)) {var success = db.                Droptable<t> (); if (Success! = operation_success) {//TODO log Error} RE            Turn success = = Operation_success; }} public static bool Trycreatetable<t> () {using (var db = new Sqlite.sqliteconnec tion (DBPath)) {var table = db. GetTableInfo (typeof (T).                Name); if (table! = null && table.                Count > 0) {return false; } db.                Createtable<t> ();            return true; }} public static T-add<t> (T book) {UsinG (var db = new Sqlite.sqliteconnection (DBPath)) {var success = db.                Insert (book);            if (Success! = operation_success) {//todo error log}}        return book; public static T deletebyid<t> (Guid id) where T:basemodel, new () {using (var db = new S Qlite.sqliteconnection (DBPath)) {var record = db. Table<t> ().                FirstOrDefault (x = x.id = = Id); if (record! = null) {var success = db.                    Delete (record); if (Success! = operation_success) {//TODO error log ret                    Urn null;                } return record;                    } else {//TODO log:failed to find record with ID ' XXX '              return null;  }}} public static T updatebyid<t> (Guid ID, T updating) where T:basemodel, new () {using (var db = new Sqlite.sqliteconnection (DBPath)) {var SingleRecord = db. Table<t> ().                FirstOrDefault (x = x.id = = Id);                    if (SingleRecord! = null) {SingleRecord = updating; Singlerecord.id = Id; Restore the id var success = db.                    Update (SingleRecord); if (Success! = operation_success) {//TODO error log ret                    Urn null;                } return updating;                    } else {//TODO log failed to find record with ID ' XXX '                return null; }}} public static T updateby<t> (Expression<func<t, bool>> where, Tupdating) where T:basemodel, new () {using (var db = new Sqlite.sqliteconnection (DBPath)) { var records = db. Table<t> (). where (where).                ToList (); if (records. Count > 0) {for (int i = 0; i < records. Count; i++) {var id = records[i].                        Id;                        Records[i] = updating; Records[i]. id = ID; Restore ID} var success = db.                    UpdateAll (Records);                        if (Success! = operation_success) {//todo error log here                    return null;                } return updating;            } return null;  }} public static ienumerable<t> all<t> () where t:new () {using (var db = new  Sqlite.sqliteconnection (DBPath)) {              Return DB. Table<t> ().            ToList (); }} public static ienumerable<t> getby<t> (expression<func<t, bool>> prediction) wher e t:new () {using (var db = new Sqlite.sqliteconnection (DBPath)) {return Enu Merable. ToList (db. Table<t> ().            Where (prediction)); }        }    }

5. Use procedure

Class Program {static void Main (string[] args) {sqlitehelper.trydroptable<book> ();            Create a table var Createresult = sqlitehelper.trycreatetable<book> ();            Console.WriteLine ("First time creating table ' book ' Result:" +createresult);            Try create it again Createresult = sqlitehelper.trycreatetable<book> ();            Console.WriteLine ("2nd time Creating table ' book ' Result:" + createresult);            Try add record var Firstrecord = Sqlitehelper.add (new book ("First", "AAA", 100));            Console.WriteLine ("First book added:");            Console.WriteLine (Firstrecord); Try update by id var updatedfirst = Sqlitehelper.updatebyid (firstrecord.id, new book ("Updated First", "Aaa_u            Pdated ", 101));            Console.WriteLine ("Updated first record:");            Console.WriteLine (Updatedfirst); Add another record VAR Secondrecord = Sqlitehelper.add (new book ("Second", "BBB", 200));            Console.WriteLine ("2nd book added:");            Console.WriteLine (Secondrecord); Try update by var Updatedsecond = Sqlitehelper.updateby (x=> x.title = = Secondrecord.titl            E && X.author = = Secondrecord.author, new book ("Updated 2nd", "bbb_updated", 201));            Console.WriteLine ("Updated 2nd record:");            Console.WriteLine (Updatedsecond);            Try Delete first var deleted = sqlitehelper.deletebyid<book> (firstrecord.id);            Console.WriteLine ("First record deleted.");            All Records:Console.WriteLine ("All Records:");            var all = sqlitehelper.all<book> ();            foreach (Var record in all) {Console.WriteLine (record);        } console.readkey (); }    }


The above is the content of C # Sqlite local storage details, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.