본문 바로가기
프로그래밍/WPF

[WPF] SQLite 로컬 DB 샘플

간단하게 데이터를 저장하고 싶은데 텍스트 파일로 저장하긴 귀찮고 관계형 데이터베이스 서버 놓긴 너무 커진다

싶을 때 사용할만한 로컬 DB인 SQLite를 사용해본다.

 

 


 

준비물

 

SQLite 바이너리 파일

다운로드 http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

 

System.Data.SQLite: Downloads Page

All downloadable packages on this web page that do not include the word "static" in their file name require the appropriate version (e.g. 2005, 2008, 2010, 2012, 2013, 2015, 2017) of the Microsoft Visual C++ Runtime Library, to be successfully installed on

system.data.sqlite.org

사이트에서 각자 버전에 맞는 dll을 다운받자

 

 

 

본 샘플은 .Net Framework 4.6이기에  4.6용 바이너리 zip 파일 받아서 dll만 프로젝트에 참조 시켜줘도 잘 돌아갔다.

 

본 샘플은 sqlite 사용법 숙지를 위해 만들었으므로 패턴 신경안쓰고 xaml 밑 cs에 코드를 전부 작성하였음.

 

 


 

 

 

프로젝트 이름

WPF_SqliteDemo

 

개발환경

Visual Studio 2017

.Net FrameWork 4.6.1

x64 전용

 

테이블 생성부

using (SQLiteConnection conn = new SQLiteConnection(connString))
{
  conn.SetPassword(myPw);
  conn.Open();

  string sql = "CREATE TABLE members ( name varchar(20), age int)";

  SQLiteCommand command = new SQLiteCommand(sql, conn);
  int result = command.ExecuteNonQuery();

  command.Dispose();
}

 

데이터 삽입부

using (SQLiteConnection conn = new SQLiteConnection(connString + Password(myPw)))
{
  conn.Open();

  // 필드에 데이터 추가
  string sql = "INSERT INTO members (name, age) values ('" + vo.Name + "'," + vo.Age + ")";
  SQLiteCommand command = new SQLiteCommand(sql, conn);
  result = command.ExecuteNonQuery();

  command.Dispose();
}

 

 

테이터 출력부

using (SQLiteConnection conn = new SQLiteConnection(connString + Password(myPw)))
{
  conn.Open();

  string sql = "SELECT * FROM members";
  SQLiteCommand command = new SQLiteCommand(sql, conn);

  //  리더로 읽기
  SQLiteDataReader rdr = command.ExecuteReader();
  while (rdr.Read())
  {
  	memList.Add(new MembersVO(rdr["name"].ToString(), rdr["age"].ToString()));
  }

  rdr.Close();
  command.Dispose();
}

 


 

 

코드 파일

 

WPF_SqliteDemo.zip
1.07MB