C# SQLite 로컬 저장소에 대한 자세한 소개

黄舟
풀어 주다: 2017-02-28 11:32:08
원래의
1521명이 탐색했습니다.

1. 다음에서 sqlite dll을 다운로드하세요:

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

Windows 버전:

http://www.sqlite.org/2016/sqlite-dll-win32-x86-3130000.zip
로그인 후 복사

2. sqlite3.dll을 bin 디렉터리에 복사합니다

3. nuget 설치: Install-Package sqlite-net
설치 후 SQLite.CS 및 SQLiteAsync.cs를 찾을 수 있습니다
4. 데모 코드:
4.1 추상 기본 모델 생성:

public abstract class BaseModel
    {
        [PrimaryKey]
        public Guid Id { get; set; }


        protected BaseModel()
        {
            Id = Guid.NewGuid();
        }
    }
로그인 후 복사

4.2 테스트 모델

 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 도우미 클래스 생성

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
                }


                return success == OPERATION_SUCCESS;
            }
        }


        public static bool TryCreateTable<T>()
        {
            using (var db = new SQLite.SQLiteConnection(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 SQLite.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
                        return null;
                    }
                    return record;
                }
                else
                {
                    // TODO log : failed to find record with id &#39;XXX&#39;
                    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
                        return null;
                    }
                    return updating;
                }
                else
                {
                    // TODO log  failed to find record with id &#39;XXX&#39;
                    return null;
                }
            }
        }


        public static T UpdateBy<T>(Expression<Func<T, bool>> where, T updating) 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) where T: new()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                return Enumerable.ToList(db.Table<T>().Where(prediction));
            }
        }
    }
로그인 후 복사

5. 사용과정

class Program
    {
        static void Main(string[] args)
        {
            SqliteHelper.TryDropTable<Book>();


            // create a table
            var createResult = SqliteHelper.TryCreateTable<Book>();
            Console.WriteLine("First time creating table &#39;Book&#39; result : " +createResult);


            // try create it again
            createResult = SqliteHelper.TryCreateTable<Book>();
            Console.WriteLine("2nd time creating table &#39;Book&#39; 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_updated", 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.Title && 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();
        }
    }
로그인 후 복사


위 내용은 C# Sqlite 로컬 스토리지에 대한 자세한 소개입니다. PHP 중국어 웹사이트(www.php.cn)에 주목하세요!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!