■ SQLite 데이터베이스를 사용하는 방법을 보여준다. (ANDROID) (UWP)
▶ Platforms/Windows/Package.appxmanifest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?xml version="1.0" encoding="utf-8"?> <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap rescap"> <Identity Publisher="CN=User Name" /> <Properties> <PublisherDisplayName>User Name</PublisherDisplayName> </Properties> <Dependencies> <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" /> <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" /> <PackageDependency Name="Microsoft.VCLibs.140.00" MinVersion="14.0.24217.0" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" /> <PackageDependency Name="Microsoft.VCLibs.140.00.UWPDesktop" MinVersion="14.0.24217.0" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" /> </Dependencies> <Resources> <Resource Language="x-generate" /> </Resources> <Applications> <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="$targetentrypoint$"> <uap:VisualElements /> </Application> </Applications> <Capabilities> <rescap:Capability Name="runFullTrust" /> </Capabilities> </Package> |
▶ Person.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using SQLite; namespace TestProject; /// <summary> /// 사람 /// </summary> [Table("people")] public class Person { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> [PrimaryKey, AutoIncrement] public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [MaxLength(250), Unique] public string Name { get; set; } #endregion } |
▶ PersonRepository.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
using SQLite; namespace TestProject; /// <summary> /// 사람 저장소 /// </summary> public class PersonRepository { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SQLite 연결 /// </summary> private SQLiteConnection connection; /// <summary> /// 데이터베이스 파일 경로 /// </summary> private string databaseFilePath; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 상태 메시지 - StatusMessage /// <summary> /// 상태 메시지 /// </summary> public string StatusMessage { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - PersonRepository(databaseFilePath) /// <summary> /// 생성자 /// </summary> /// <param name="databaseFilePath">데이터베이스 파일 경로</param> public PersonRepository(string databaseFilePath) { this.databaseFilePath = databaseFilePath; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 사람 추가하기 - AddPerson(name) /// <summary> /// 사람 추가하기 /// </summary> /// <param name="name">성명</param> public void AddPerson(string name) { try { Initialize(); if(string.IsNullOrEmpty(name)) { throw new Exception("성명을 입력해 주시기 바랍니다."); } int recordCount = this.connection.Insert(new Person { Name = name }); StatusMessage = string.Format("레코드 {0}건이 추가되었습니다(성명 : {1}).", recordCount, name); } catch(Exception exception) { StatusMessage = string.Format("{0} 추가시 에러가 발생했습니다 : {1}", name, exception.Message); } } #endregion #region 모든 사람 리스트 구하기 - GetAllPersonList() /// <summary> /// 모든 사람 리스트 구하기 /// </summary> /// <returns>모든 사람 리스트</returns> public List<Person> GetAllPersonList() { try { Initialize(); return this.connection.Table<Person>().ToList(); } catch(Exception exception) { StatusMessage = string.Format("데이터 조회시 에러가 발생했습니다 : {0}", exception.Message); } return new List<Person>(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 초기화하기 - Initialize() /// <summary> /// 초기화하기 /// </summary> private void Initialize() { if(this.connection != null) { return; } this.connection = new SQLiteConnection(databaseFilePath); this.connection.CreateTable<Person>(); } #endregion } |
▶ FileHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
namespace TestProject; /// <summary> /// 파일 헬퍼 /// </summary> public class FileHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 데이터베이스 파일 경로 구하기 - GetDatabaseFilePath(fileName) /// <summary> /// 데이터베이스 파일 경로 구하기 /// </summary> /// <param name="fileName">파일명</param> /// <returns>데이터베이스 파일 경로</returns> public static string GetDatabaseFilePath(string fileName) { return Path.Combine(FileSystem.AppDataDirectory, fileName); } #endregion } |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" BackgroundColor="White"> <Grid Margin="10" RowSpacing="10" ColumnSpacing="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Entry x:Name="nameEntry" Grid.Row="0" Placeholder="성명을 입력해 주시기 바랍니다." /> <Button x:Name="addButtnon" Grid.Row="1" Text="추가하기" /> <Label x:Name="statusMessageLabel" Grid.Row="2" /> <Button x:Name="getButton" Grid.Row="3" Text="조회하기" /> <CollectionView x:Name="collectionView" Grid.Row="4"> <CollectionView.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="2*" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Text="{Binding ID}" /> <Label Grid.Column="1" Text="{Binding Name}" /> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </Grid> </ContentPage> |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.addButtnon.Clicked += addButton_Clicked; this.getButton.Clicked += getButton_Clicked; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 추가하기 버튼 클릭시 처리하기 - addButton_Clicked(sender, e) /// <summary> /// 추가하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> public void addButton_Clicked(object sender, EventArgs e) { this.statusMessageLabel.Text = string.Empty; App.PersonRepository.AddPerson(this.nameEntry.Text); this.statusMessageLabel.Text = App.PersonRepository.StatusMessage; } #endregion #region 조회하기 버튼 클릭시 처리하기 - getButton_Clicked(sender, e) /// <summary> /// 조회하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> public void getButton_Clicked(object sender, EventArgs e) { this.statusMessageLabel.Text = string.Empty; List<Person> personList = App.PersonRepository.GetAllPersonList(); this.collectionView.ItemsSource = personList; } #endregion } |
▶ AppShell.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="TestProject.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:TestProject" Shell.FlyoutBehavior="Disabled"> <ShellContent Title="사람" Route="MainPage" ContentTemplate="{DataTemplate local:MainPage}" /> </Shell> |
▶ App.xaml
1 2 3 4 5 6 |
<?xml version = "1.0" encoding = "UTF-8" ?> <Application x:Class="TestProject.App" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" /> |
▶ App.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
namespace TestProject; /// <summary> /// 앱 /// </summary> public partial class App : Application { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 사람 저장소 - PersonRepository /// <summary> /// 사람 저장소 /// </summary> public static PersonRepository PersonRepository { get; private set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - App(personRepository) /// <summary> /// 생성자 /// </summary> /// <param name="personRepository">사람 저장소</param> public App(PersonRepository personRepository) { InitializeComponent(); MainPage = new AppShell(); PersonRepository = personRepository; } #endregion } |
▶ MauiProgram.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
namespace TestProject; /// <summary> /// MAUI 프로그램 /// </summary> public static class MauiProgram { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region MAUI 앱 생성하기 - CreateMauiApp() /// <summary> /// MAUI 앱 생성하기 /// </summary> /// <returns>MAUI 앱</returns> public static MauiApp CreateMauiApp() { MauiAppBuilder builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts ( fontCollection => { fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" ); fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); } ); string databaseFilePath = FileHelper.GetDatabaseFilePath("people.db3"); builder.Services.AddSingleton<PersonRepository> ( serviceProvider => ActivatorUtilities.CreateInstance<PersonRepository>(serviceProvider, databaseFilePath) ); return builder.Build(); } #endregion } |