michgan software studio

'SQLite'에 해당되는 글 1건

  1. 2010/01/27 [howto] SQLite C# 버전 사용법 (4)

요즘 모바일용으로 새로운 프로그램을 하나 구상하고 있는데, 데이타베이스 기능이 필수적으로 필요합니다. 물론 MS에서는 SQL Server Compact 3.5 for Windows Mobile을 공개하고 있지만, 핸드폰에 저장된 데이타베이스 파일을 PC로 옮겨서 사용하는 상황을 생각해보면, 핸드폰의 데이타와 동기화하기 위한 MS SQL Server 까지 필요하게 되더군요. 그럴 바엔 공개 라이브러리를 택하는 편이 낫겠다 싶어 조금 찾아보았습니다.

그러다 SQLite 라는 라이브러리를 발견하였습니다. 속도가 얼마나 빠른지는 모르겠지만, 완전히 public domain으로 공개된 소스라 제 마음에 쏙 들더군요. 다운 받을 수 있는 경로는 http://www.sqlite.org 입니다. 원 제작자들은 C 함수로 API를 만들어 놨습니다만, 훌륭한 사람들이 C# 용으로도 개발해 놨더군요. 이것 역시 public domain으로 공개되어 있습니다. http://sqlite.phxsoftware.com/ 에서 다운 받을 수 있습니다.

제가 테스트해본 쪽은 후자쪽입니다. 인스톨 파일을 다운 받아 설치하고, C# 프로젝트를 하나 만든 후에 Reference에 System.Data.SQLite 를 추가해줍니다.

아래는 테스트해볼 겸해서 직접 짜본 코드입니다.

데이타 베이스 파일을 하나 만들고, table을 생성한 뒤에, C:\windows 밑에 있는 파일 목록을 집어 넣습니다. 이후에 1024 ~ 1048576 의 크기를 갖는 파일을 SELECT 하는데, ORDER BY Size로 정렬합니다.

일단 이 정도만 되더라도 모바일에서 쓰기엔 괜찮을거 같다는 생각이 듭니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.IO;

namespace sqlitecs
{
    class Program
    {
        static void Main(string[] args)
        {
            //  Creating a database.
            SQLiteConnection.CreateFile("test.db");

            //  Open the database.
            using (var connection = new SQLiteConnection("Data Source=test.db"))
            {
                connection.Open();                 try
                {
                    //  Create table.
                    using (SQLiteCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "CREATE TABLE File (Name text, Size bigint, Modified datetime);";
                        command.ExecuteNonQuery();
                    }

                    //  Insert datas.
                    using (SQLiteCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO File VALUES (?,?,?);";
                        SQLiteParameter p1 = new SQLiteParameter();
                        SQLiteParameter p2 = new SQLiteParameter();
                        SQLiteParameter p3 = new SQLiteParameter();
                        command.Parameters.Add(p1);
                        command.Parameters.Add(p2);
                        command.Parameters.Add(p3);

                        foreach (var fi in (new DirectoryInfo("c:\\Windows")).GetFiles())
                        {
                            p1.Value = fi.Name;
                            p2.Value = fi.Length;
                            p3.Value = fi.LastWriteTimeUtc;
                            command.ExecuteNonQuery();
                        }
                    }

                    //  Select files by its size between 1k and 1M
                    using (SQLiteCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "SELECT * from File where Size >= 1024 and Size <= 1048576 order by Size;";
                        using (SQLiteDataReader reader = command.ExecuteReader())
                        {
                            while(reader.HasRows && reader.Read())
                            {
                                Console.WriteLine("{0}, {1}, {2}", reader.GetString(0), reader.GetInt64(1), reader.GetDateTime(2));
                            }
                        }
                    }
                }
                finally
                {
                    connection.Close();
                }
            }
        }
    }
}



저작자 표시 비영리 동일 조건 변경 허락
  1. 김상진  댓글주소  수정/삭제  댓글쓰기

    안녕하세요 이번에 윈도우 모바일을 처음으로 개발하게 됬는데요

    c#에서 sqlite를 사용하려고 위와같이 따라 했는데 아래와 같은 오류가 나오더라구요.

    무슨 에러일 까요? wm쪽은 처음이다 보니 경험도 없어 잘 모르겠네요.ㅠㅠ

    --------------------------------------------------------------------
    'System.Data.Common.DbConnection' 형식이 참조되지 않은 어셈블리에 정의되었습니다.
    'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    어셈블리에 참조를 추가해야 합니다.

    2010/02/22 10:48
  2. 세상살기  댓글주소  수정/삭제  댓글쓰기

    좋은 정보 감사합니다..

    다만, 위의 Insert 문장은 트랜잭션 처리를 건별로 자동적으로 수행하기 때문에 속도가 무척 느립니다. c 버젼이나 php 버젼등에서는 begin ; loop {insert } ; commit ; 이런 순으로 바꾸어서 처리해서 속도를 올리죠.

    C#은 없는 줄 알았는데 아래처럼 하면 insert 속도가 대략 200배 정도 차이가 날 정도로 빨라지네요..;;;

    using (SQLiteTransaction dbTrans = connection.BeginTransaction())
    {
    using (SQLiteCommand command = connection.CreateCommand())
    {
    command.CommandText = "INSERT INTO File VALUES (?,?,?);";
    SQLiteParameter p1 = new SQLiteParameter();
    SQLiteParameter p2 = new SQLiteParameter();
    SQLiteParameter p3 = new SQLiteParameter();
    command.Parameters.Add(p1);
    command.Parameters.Add(p2);
    command.Parameters.Add(p3);
    foreach (var fi in (new DirectoryInfo("c:\\Windows")).GetFiles())
    {
    p1.Value = fi.Name;
    p2.Value = fi.Length;
    p3.Value = fi.LastWriteTimeUtc;
    command.ExecuteNonQuery();
    label1.Text = "B-INSERT TABLE";
    }
    }
    dbTrans.Commit();
    }

    2010/03/25 15:18

1 
BLOG main image
michgan software studio
Copyright (c) 1992-2008 michgan
by michgan

카테고리

분류 전체보기 (60)
release (34)
document (23)
review (1)