0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WindowsでMono.Data.Sqliteを使う

Last updated at Posted at 2020-05-28

Mono には SQLite のバインディングが付属しています。それを Windows の .NET Framework から使ってみます。

シリーズの記事です。

  1. SQLitePCLRawが動作する組み合わせを探る
  2. Microsoft.Data.SqliteをWindowsとWSLで共有する
  3. WindowsでMono.Data.Sqliteを使う ← この記事
  4. Mono.Data.SqliteでDapperを使う

概要

これまで SQLitePCLRaw と Microsoft.Data.Sqlite を試して来ました。

パッケージの依存関係やバージョンなど、細かいことを気にしないとうまく動きませんでした。依存するライブラリも多く、ちょっとしたスクリプトから気軽に使えるという感じではありません。

Mono には System.Data.SQLite からフォークした Mono.Data.Sqlite が付属します。

2005 年に、Robert Simpson は ADO.NET 2.0 用の SQLite プロバイダーである System.Data.SQLite を作成しました。 2010 年に、SQLite チームがプロジェクトのメンテナンスと開発を引き継ぎました。 また、2007 年に Mono チームがコードを Mono.Data.Sqlite としてフォークしたことも注目すべき点です。

これが Windows でも動けば、環境構築が楽そうです。

テスト

前回の記事と同じテスト DB を使用します。

hello.sql
CREATE TABLE user (id INT, name text);
INSERT INTO user VALUES (1,"Foo"),(2,"Bar");
作成
sqlite3 hello.db ".read hello.sql"

テストコードを移植します。どちらも ADO.NET に準拠しているため基本的な使い方は同じです。ライブラリの参照とファイルの指定を書き換えただけです。

test.fsx
# r "Mono.Data.Sqlite.dll"
open Mono.Data.Sqlite
let id = 1
do
    use connection = new SqliteConnection("URI=file:hello.db")
    connection.Open()

    let command = connection.CreateCommand()
    command.CommandText <- @"
        SELECT name
        FROM user
        WHERE id = $id"
    command.Parameters.AddWithValue("$id", id) |> ignore

    use reader = command.ExecuteReader()
    while reader.Read() do
        let name = reader.GetString 0
        printfn "Hello, %s!" name

Mono で実行します。バンドルされているので環境構築の手間がありません。

実行結果
$ fsharpi test.fsx
Hello, Foo!
$ fsharpc test.fsx
Microsoft (R) F# Compiler version 10.2.3 for F# 4.5
Copyright (c) Microsoft Corporation. All Rights Reserved.
$ mono test.exe
Hello, Foo!

Windows で使う

Windows の .NET Framework から使おうとすると、ライブラリが見付からないためエラーになります。

$ ./test.exe

ハンドルされていない例外: System.IO.FileNotFoundException: ファイルまたはアセンブリ 'Mono.Data.Sqlite, Vers
ion=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756'、またはその依存関係の 1 つが読み込めませんで
した。指定されたファイルが見つかりません。
   場所 <StartupCode$test>.$Test$fsx.main@()

SQLite の公式サイトから Windows 用の DLL をダウンロードして置きます。

Mono のライブラリをコピーします。

cp /usr/lib/mono/4.5/Mono.Data.Sqlite.dll .

これで無事に動きます。

$ fsiAnyCpu.exe test.fsx
Hello, Foo!
$ ./test.exe
Hello, Foo!

ファイルを 2 つコピーするだけなので、お手軽に使うには良さそうです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?