DHJJ [Hatsune's Journal Japan] blog

Hatsune's Journal Japan blog

目次

Blog 利用状況

ニュース

最新ツイート

運営サイト

Hatsune's Journal Japan
DHJJ

著作など

資格など

OCP
MCP

書庫

日記カテゴリ

わんくま同盟

SQLiteを使ったWindows Mobileアプリを作成する

System.Data.SQLiteには、.NET Compact Framework用のクラスライブラリ(こちらも接続コンポーネントではなくSQLiteそのもの)も付属しています。

Windows Mobileアプリを新規に作成して、実機(emone α)に配置して動作するかどうかを確認してみます。

サンプル用プロジェクトの作成

.NET Framework 2.0でWindows Mobile 5.0 Pocket PC SDKをターゲットにしてあたらしいプロジェクトを作成します。

参照設定で、System.Data.SQLite.dllを指定します。ここで表示されているのは.NET Compact Framewok用のクラスライブラリだけですので、クラスライブラリの場所も.NET Compact Framework用のものであることが分かります。

image

System.Data.SQLite.dllは、配置の事を考慮してローカルにコピーするように設定します。

image

さらに「」で作成したtest.dbファイルもプロジェクトに加えて、[出力ディレクトリにコピー]プロパティを「新しいときはコピーする」に設定します。

image image

これで、プロジェクトの準備はできました。

Visual Basic 2008でプログラミングする

System.Data.SQLiteは、ADO.NET 2.0相当のデータアクセスメソッドをもっているので、VB2005でもVB2008でも同じようにプログラミングできます。そこで次のような画面をもつサンプルプログラムを作成して、接続、データ取得、データ更新のコードを確認してみましょう。

image

SQLiteのファイルと接続する

Imports System.Data.SQLite
Public Class SampSQLite
  Private Ds As New DataSet
  Private ConnectionString As String = "data source={0}"

  Private Sub SampSQLiteCF_Load(ByVal sender As Object, _
                                ByVal e As System.EventArgs) _
                                Handles MyBase.Load
    ConnectionString = String.Format(ConnectionString, _
                                     System.IO.Path.Combine(GetCurrentDirectory, _
                                                            "test.db"))
  End Sub

  Private Shared Function GetCurrentDirectory() As String
    Dim fqn As String = System.Reflection.Assembly. _
                          GetExecutingAssembly. _
                            ManifestModule. _
                              FullyQualifiedName
    Return New System.IO.FileInfo(fqn).DirectoryName
  End Function

  Private Sub Connect_Button_Click(ByVal sender As System.Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles Connect_Button.Click
    Cursor.Current = Cursors.WaitCursor
    Using _cn As New SQLiteConnection
      Try
        _cn.ConnectionString = ConnectionString
        _cn.Open()
        MessageBox.Show("Open成功", Me.Text)
      Catch ex As Exception
        MessageBox.Show(ex.Message, Me.Text)
      Finally
        Try
          _cn.Close()
        Catch ex As Exception
        End Try
        Cursor.Current = Cursors.Default
      End Try
    End Using
  End Sub
End Class

カレントディレクトリを取得する部分だけは.NET Compact Frameworkに合わせて書き足してはいますが、その他の部分についてはWindowsアプリケーションのときと同一のコードです。

Windows Mobile 5.0 Pokect PC R2 エミュレータでの動作確認

エミュレータに対して配置を行っても、アセンブリだけは配置されますが、System.Data.SQLite.dllやtest.dbは配置されません。

そこで[ファイル]-[構成]メニューをクリックして共有フォルダを設定して、エミュレータのファイルエクスプローラで不足しているファイルを手動配置します。

image

image

エミュテータを使う場合、作成したアセンブリとtest.db(SQLiteファイル)のみで動作します。

実機(emone α)の動作確認

PC同期モードでUSBを接続してからアセンブリを配置したら、test.db(SQLiteファイル)を含め次のファイルをコピーします。

  • System.Data.SQLite.dll(114KB)
  • SQLite.Interop.060.DLL(438KB)
  • test.db
SQLiteのテーブルから値を取得する

ADO.NETを使ってテーブルから値を取得する方法には、DataReaderを使う方法とDataAdapterを使う方法があります。ここでは、DataAdapterを使う方法をご紹介します。

Imports System.Data.SQLite
Public Class SampSQLite
  Private Ds As New DataSet
  Private ConnectionString As String = "data source={0}"

  Private Sub SampSQLiteCF_Load(ByVal sender As Object, _
                                ByVal e As System.EventArgs) _
                                Handles MyBase.Load
    ConnectionString = String.Format(ConnectionString, _
                                     System.IO.Path.Combine(GetCurrentDirectory, _
                                                            "test.db"))
  End Sub

  Private Shared Function GetCurrentDirectory() As String
    Dim fqn As String = System.Reflection.Assembly. _
                          GetExecutingAssembly. _
                            ManifestModule. _
                              FullyQualifiedName
    Return New System.IO.FileInfo(fqn).DirectoryName
  End Function

  Private Sub GetRecords_Button_Click(ByVal sender As System.Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles GetRecords_Button.Click
    Cursor.Current = Cursors.WaitCursor
    Using _cn As New SQLiteConnection
      Try
        _cn.ConnectionString = ConnectionString
        _cn.Open()
        Using _cmd As New SQLiteCommand("SELECT * FROM EMP", _cn)
          Using _da As New SQLiteDataAdapter(_cmd)
            _da.Fill(Ds, "EMP")
            Me.Result_Grid.DataSource = Ds.Tables("EMP")
          End Using
        End Using
      Catch ex As Exception
        MessageBox.Show(ex.Message, Me.Text)
      Finally
        Try
          _cn.Close()
        Catch ex As Exception
        End Try
        Cursor.Current = Cursors.Default
      End Try
    End Using
  End Sub
End Class

データを取得するためには、以下の手順を実行します。

  1. SQLiteConnectionをOpen SQLiteCommandにSELECT文を設定
  2. SELECT文を設定したSQLiteCommandを指定してSQLiteDataAdapterを生成
  3. SQLiteDataAdatpterのFilllメソッドによりDataSetにレコード設定

DataSetに入ってしまえば、データの取得元は関係なくなりますので、DataGridViewのデータソースとして指定すればテーブルの内容をグリッド表示できます。

SQLiteのテーブルの値を更新する

Imports System.Data.SQLite
Public Class SampSQLite
  Private Ds As New DataSet
  Private ConnectionString As String = "data source={0}"

  Private Sub SampSQLite_Shown(ByVal sender As Object, _
                               ByVal e As System.EventArgs) _
                               Handles Me.Shown
    ConnectionString = String.Format(ConnectionString, _
                                     System.IO.Path.Combine(My.Application.Info.DirectoryPath, _
                                                            "test.db"))
  End Sub

  Private Sub SetRecords_Button_Click(ByVal sender As System.Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles SetRecords_Button.Click
    Cursor.Current = Cursors.WaitCursor
    Using _cn As New SQLiteConnection
      Try
        _cn.ConnectionString = ConnectionString
        _cn.Open()
        Using _tr As SQLiteTransaction = _cn.BeginTransaction
          Try
            Using _cmd As New SQLiteCommand("SELECT * FROM EMP", _cn)
              _cmd.Transaction = _tr      '###重要###
              Using _da As New SQLiteDataAdapter(_cmd)
                Using cb As New SQLiteCommandBuilder(_da)
                  cb.SetAllValues = False
                  cb.ConflictOption = Data.ConflictOption.OverwriteChanges
                  _da.UpdateCommand = cb.GetUpdateCommand()
                  _da.InsertCommand = cb.GetInsertCommand()
                  _da.DeleteCommand = cb.GetDeleteCommand()
                  MessageBox.Show(_da.UpdateCommand.CommandText, Me.Text)
                  MessageBox.Show(_da.InsertCommand.CommandText, Me.Text)
                  MessageBox.Show(_da.DeleteCommand.CommandText, Me.Text)
                  _da.Update(Ds, "EMP")
                  MessageBox.Show("Update", Me.Text)
                End Using
              End Using
            End Using
            _tr.Commit()
          Catch ex As Exception
            MessageBox.Show(ex.Message, Me.Text)
            _tr.Rollback()
          Finally
          End Try
        End Using
      Catch ex As Exception
        MessageBox.Show(ex.Message, Me.Text)
      Finally
        Try
          _cn.Close()
        Catch ex As Exception
        End Try
      End Try
      Cursor.Current = Cursors.Default
    End Using
  End Sub
End Class

残念ながら、.NET Compact FrameworkのDataGridはデータ参照のみで更新ができません。更新するためには、更新用別画面を作成することになるようです。

今回は省略しますが、別画面で設定した値をDataSetに反映させれば、あとはこのコードで更新が行えます。

このコードで重要な点はつぎのような事になります。

DataSetからの反映にもSQLiteDataAdapterを使いますが、SELECT文ではなくUPDATE、INSERT、DELETEのSQL文が必要です。重要なのは、反映時にどのSQL文を使うかはSQLiteDataAdapterの内部実装になるので、必ず3つとも設定しておかないと実行時にエラーが発生する危険性があることを忘れないようにしてください。

3つのSQL文はそれぞれ記述してもいいのですが、SQLiteCommandBuilderを使って、SELECT文から自動生成するのが楽です。

SetAllValuesプロパティとConflictOptionプロパティをサンプルコードのように設定すれば次のようなSQL文を生成してくれます。

image

image

image

DataAdapterでの更新にはトランザクションを設定が必須


SQLiteに限らず、ADO.NETのDataAdapterでデータ更新をする場合、かならず明示的にトランザクションを開始して、Updateメソッドが成功したらCommit、失敗したらRollBackする必要があります。

なぜならば、データ更新対象が常に1つになるような画面構成ならば1SQL文の実行ですみますが、グリッド表示のように削除、追加、複数行の変更が行われる可能性がある場合、DataAdapterのUpdateメソッドの内部ではUPDATE、INSERT、DELETEのSQL文を別個に発行しているからです。

これは非常に重要な点です。忘れないようにしましょう。

投稿日時 : 2008年10月16日 18:30

Feedback

# Very great post. I just stumbled upon your weblog and wanted to say that I have truly loved surfing around your weblog posts. In any case I will be subscribing to your feed and I am hoping you write once more soon! 2018/10/06 23:12 Very great post. I just stumbled upon your weblog

Very great post. I just stumbled upon your
weblog and wanted to say that I have truly loved surfing around your weblog posts.
In any case I will be subscribing to your feed and I am hoping you write once more soon!

# Ridiculous quest there. What happened after? Take care! 2018/10/09 0:57 Ridiculous quest there. What happened after? Take

Ridiculous quest there. What happened after? Take care!

# Your style is very unique in comparison to other folks I have read stuff from. Many thanks for posting when you have the opportunity, Guess I'll just bookmark this blog. 2018/10/28 1:27 Your style is very unique in comparison to other f

Your style is very unique in comparison to other folks I have read stuff from.

Many thanks for posting when you have the opportunity, Guess I'll just bookmark this blog.

# I do not even understand how I stopped up here, however I believed this put up was once good. I don't know who you're however certainly you're going to a famous blogger if you are not already. Cheers! 2018/12/07 6:32 I do not even understand how I stopped up here, ho

I do not even understand how I stopped up here,
however I believed this put up was once good. I don't know who you're however certainly you're going to
a famous blogger if you are not already. Cheers!

# great publish, very informative. I wonder why the opposite experts of this sector do not understand this. You must continue your writing. I am sure, you've a huge readers' base already! 2019/05/06 17:21 great publish, very informative. I wonder why the

great publish, very informative. I wonder why the opposite experts of this sector do not
understand this. You must continue your writing.
I am sure, you've a huge readers' base already!

# Hello i am kavin, its my first time to commenting anywhere, when i read this piece of writing i thought i could also create comment due to this sensible post. 2019/05/29 11:37 Hello i am kavin, its my first time to commenting

Hello i am kavin, its my first time to commenting anywhere, when i read this piece of writing i thought i could also create comment due to this
sensible post.

# I visited multiple web sites but the audio feature for audio songs existing at this website is really wonderful. 2019/05/30 21:04 I visited multiple web sites but the audio feature

I visited multiple web sites but the audio feature for audio songs existing at this
website is really wonderful.

# Wow, this piece of writing is good, my younger sister is analyzing these things, thus I am going to tell her. 2019/06/04 0:23 Wow, this piece of writing is good, my younger sis

Wow, this piece of writing is good, my younger sister
is analyzing these things, thus I am going to tell her.

# I am sure this article has touched all the internet visitors, its really really good article on building up new webpage. 2019/06/06 6:11 I am sure this article has touched all the interne

I am sure this article has touched all the internet visitors, its really really good article
on building up new webpage.

# I like the valuable info you provide in your articles. I'll bookmark your weblog and check again here regularly. I'm quite certain I will learn a lot of new stuff right here! Best of luck for the next! 2019/06/07 19:20 I like the valuable info you provide in your artic

I like the valuable info you provide in your
articles. I'll bookmark your weblog and check again here regularly.

I'm quite certain I will learn a lot of new stuff right here!
Best of luck for the next!

# Excellent post however , I was wanting to know if you could write a litte more on this subject? I'd be very grateful if you could elaborate a little bit more. Many thanks! 2021/08/24 16:57 Excellent post however , I was wanting to know if

Excellent post however , I was wanting to know if you
could write a litte more on this subject? I'd be very grateful if
you could elaborate a little bit more. Many thanks!

# Informative article, totally what I was looking for. 2021/09/03 12:23 Informative article, totally what I was looking fo

Informative article, totally what I was looking for.

# Informative article, totally what I was looking for. 2021/09/03 12:24 Informative article, totally what I was looking fo

Informative article, totally what I was looking for.

# Informative article, totally what I was looking for. 2021/09/03 12:25 Informative article, totally what I was looking fo

Informative article, totally what I was looking for.

# Informative article, totally what I was looking for. 2021/09/03 12:26 Informative article, totally what I was looking fo

Informative article, totally what I was looking for.

# We stumbled over here from a different website and thought I might as well check things out. I like what I see so now i'm following you. Look forward to looking at your web page yet again. 2021/09/06 14:20 We stumbled over here from a different website and

We stumbled over here from a different website and
thought I might as well check things out. I like what I see so now i'm
following you. Look forward to looking at your web page yet again.

# What's up to every body, it's my first go to see of this weblog; this weblog includes awesome and genuinely excellent information for visitors. quest bars http://bit.ly/3C2tkMR quest bars 2021/09/11 10:06 What's up to every body, it's my first go to see

What's up to every body, it's my first go to see of this weblog; this weblog includes awesome and genuinely
excellent information for visitors. quest bars http://bit.ly/3C2tkMR quest bars

# Link exchange is nothing else however it is only placing the other person's blog link on your page at suitable place and other person will also do same for you. 2021/11/12 22:39 Link exchange is nothing else however it is only

Link exchange is nothing else however it is only
placing the other person's blog link on your page at suitable place and other person will also do
same for you.

# Link exchange is nothing else but it is simply placing the other person's website link on your page at proper place and other person will also do similar for you. 2021/12/24 19:46 Link exchange is nothing else but it is simply pla

Link exchange is nothing else but it is simply placing the other person's website
link on your page at proper place and other person will also do similar for you.

# what to write my college essay on n668ep 2022/09/04 15:39 Charlosmox


You have made the point! https://definitionessays.com/ myself as a writer essay

# essay writers wanted b38vom 2022/09/08 23:14 Charlosmox


Wow a good deal of superb information! https://definitionessays.com/ money can buy happiness essay

# pay someone to write my college essay y33eyp 2023/02/26 12:12 CharlesSnoff


Very good advice. With thanks!
where can i buy essay https://quality-essays.com/ where to buy essays

# professional dissertation help r230qs 2023/02/27 2:30 Robertsaids


Many thanks. Useful stuff!
undergraduate dissertation writing service https://dissertationwritingtops.com/ dissertation order of contents

# the thesis statement summarizes t82hdz 2023/03/03 1:05 Josephbried


Regards! Numerous material!
phd thesis writing services https://writingthesistops.com/ shoddy service sows the seeds of discontent thesis

# exemplary college essays p98gwb 2023/03/06 5:41 EugeneSib


Seriously a good deal of very good advice.
essay writers wanted https://helptowriteanessay.com college pressures essay https://helpmedomyxyzhomework.com

# essay writing prompts for high school s309nw 2023/03/06 20:53 EugeneSib


Regards, I enjoy it!
help me write a thesis https://topswritingservices.com essay scholarships college students https://essaywritingservicetop.com

# website for essays in english a76dpm 2023/03/07 3:22 Gregorysaipt


Good tips. Thanks.
essay writing games https://researchproposalforphd.com top rated essay writing service https://writingpaperforme.com

# buy essays cheap s46boj 2023/03/08 19:24 EugeneSib


Thanks a lot. Numerous knowledge.
descriptive writing essay https://studentessaywriting.com dissertation assistance writing https://bestonlinepaperwritingservices.com

# funny college essay p314ks 2023/03/09 11:39 EugeneSib

You actually explained it really well!
colleges essays https://essaywritingservicetop.com disseratation https://paperwritingservicecheap.com

# dissertation psychology s47fbp 2023/03/09 21:35 Gregorysaipt


Wow all kinds of awesome data.
how to write a great narrative essay https://writinganessaycollegeservice.com writing essays for college applications https://quality-essays.com

# how to write an exemplification essay c99uum 2023/03/10 2:16 EugeneSib


Great forum posts. Regards!
dissertions https://helptowriteanessay.com cambridge essay service https://custompaperwritersservices.com

# where to buy essays h19iyg 2023/03/11 7:39 EugeneSib

You actually reported that perfectly.
ma dissertations https://hireawriterforanessay.com writing persuasive essay https://buyanessayscheaponline.com

# how to write an abstract for an essay r82ble 2023/03/12 13:16 EugeneSib

You mentioned it effectively.
assignment essay help https://payforanessaysonline.com writing an application essay https://domycollegehomeworkforme.com

# The plugins developed for WordPress 2023/05/09 23:55 Justas

The plugins developed for WordPress serve to enhance the features and functions of a WordPress website, allowing you to build your awesome and functional site https://t.me/wpigaming/648 Customise WordPress with powerful, professional and intuitive fields.

タイトル
名前
Url
コメント