728x90
728x170

이번 시간에는 DataBase 관련 첫번째 시간으로 SQLite 를 알아보도록 하겠습니다.

보통 서버와 연결하지 않고 로컬로만 어떤 데이터를 다룰 때는 SQLite 가 가장 편한 것 같습니다.

이번에 소개할건 PlugIn.SQLite 입니다. (Nuget 에서 받을수 있습니다.)

 

프로젝트를 열고 솔루션의 NutGet 패키지 관리로 들어갑니다.

PlugIn.SQLite 로 검색하면 아래처럼 하나가 나옵니다.

오른쪽에 모두 체크하고 설치를 클릭합니다.

확인을 하게되면

각각 프로젝트 별로 (UWP 제외) SQLite 폴더가 생성되고 내부에 코딩이 자동으로 들어가 있게됩니다.

각각 프로젝트에 맞게 namespace 등은 변경해 주어야합니다.

[ Android ]

코드 내용 (프로젝트에 맞게 변경이 완료된 내용입니다.)

using System.IO;
using SQLite;
using Xamarin.Forms;
using XamarinFormsStudy.Android;

[assembly: Dependency(typeof(SQLite_Android))]

namespace XamarinFormsStudy.Android
{
    public class SQLite_Android : ISQLite
    {
        public SQLite_Android() { }
        public SQLiteConnection GetConnection()
        {
            var sqliteFilename = "MySQLiteDB.db3";
            string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
            var path = Path.Combine(documentsPath, sqliteFilename);
            // Create the connection
            var conn = new SQLiteConnection(path);
            // Return the database connection
            return conn;
        }
    }
}

[ iOS ]

코드내용 (프로젝트에 맞게 변경이 완료된 내용입니다.)

using System;
using System.IO;
using SQLite;
using Xamarin.Forms;
using XamarinFormsStudy.iOS;

[assembly: Dependency(typeof(SQLite_iOS))]

namespace XamarinFormsStudy.iOS
{
    public class SQLite_iOS : ISQLite
    {

        public SQLite_iOS()
        {
        }

        public SQLiteConnection GetConnection()
        {
            var sqliteFilename = "MySQLiteDB.db3";
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
            string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
            var path = Path.Combine(libraryPath, sqliteFilename);
            // Create the connection
            var conn = new SQLiteConnection(path);
            // Return the database connection
            return conn;
        }
    }
}

[ UWP ]

UWP 는 참조는 추가 되나 관련 파일이 자동으로 추가되지 않습니다.

수동으로 추가해 주어야합니다.

이식가능 프로젝트에 보면 'SQLite-AppSample' 폴더에 readme.txt 파일이 있는데 여기에 UWP 에 넣어야할 코딩이 나와있습니다.

UWP 프로젝트에서 클래스를 추가하고 위 코딩을 넣습니다.

당연히 프로젝트에 맞에 수정을 해야합니다.

코드 내용 (프로젝트에 맞게 변경이 완료된 내용입니다.)

using System.IO;
using Windows.Storage;
using SQLite;
using Xamarin.Forms;
using XamarinFormsStudy.UWP;

[assembly: Dependency(typeof(SQLite_Uwp))]

namespace XamarinFormsStudy.UWP
{
    public class SQLite_Uwp : ISQLite
    {
        public SQLite_Uwp()
        {
        }

        public SQLiteConnection GetConnection()
        {
            var sqliteFilename = "MySQLiteDB.db3";
            string documentsPath = ApplicationData.Current.LocalFolder.Path;
            var path = Path.Combine(documentsPath, sqliteFilename);
            // Create the connection
            var conn = new SQLiteConnection(path);
            // Return the database connection
            return conn;
        }
    }
}

 

[ 이식가능 프로젝트(PCL) ]

이식가능에 추가된 SQLite 관련된 파일중 TodoItem 은 테스트할 데이터에 대한 테이블의 형태가 정의되어있습니다.

using SQLite;

namespace XamarinFormsStudy
{
    public class TodoItem
    {

        // 키 정보이며 하나씩 증가합니다.
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }

        public string Text { get; set; }

        public bool Done { get; set; }

        public override string ToString()
        {
            return string.Format("Done : {0}, Text : {1}", Done, Text);
        }
    }
}

그리고 SQLiteSamplePage 에서는 CRUD 관련 코딩 예시가 나와있습니다.

또한 ContentPage 도 제공해 주어 바로 실행하여 확인도 가능합니다.

App.xaml 파일에서 아래 처럼 호출되도록 하고 실행해 보면

MainPage = new SQLiteSamplePage().GetSampleContentPage();

아래 와 같은 결과가 나옵니다.

데이터는 입력항목과 스위치 버튼의 true,false 값이 Add 하면 저장되고 Refresh 하게되면 저장된 값이 아래로 나열됩니다.

 

 

참고

https://www.youtube.com/watch?v=nrXmA-0NoOE&index=26&list=PLpbcUe4chE7-5t2mlamz6yB0qzAfO5Yln

GitHub > https://github.com/knagjun/XamarinForms

 

 

728x90
그리드형
Posted by kjun
,