.NET6.0, C#, コンソールアプリで Microsoft.Data.Sqlite を使って SQLite を操作する環境の構築とサンプルコードを作成してみました。
Microsoft.Data.Sqliteをインストールして実行すれば動作するだろう!と思って作業をしましたが、以下の例外が発生し、
別途、本例外を解消するためのパッケージもインストールします。
System.Exception: 'You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().'
Microsoft.Data.Sqlite を使用するので、「NuGetパッケージの管理」を使用しインストールします。
本サンプルでは、SQLitePCLRaw.bundle_e_sqlite3を利用します。
これをインストールしないと、以下の例外が発生します。
System.Exception: 'You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().'
他にもバンドルがあります。
以下のURLから各バンドルを調べてみてください。
抜粋
バンドル | 説明 |
SQLitePCLRaw.bundle_e_sqlite3 | すべてのプラットフォームで同じバージョンの SQLite を提供します。FTS4、FTS5、JSON1、R*Tree 拡張機能を含みます。 既定値です。 |
SQLitePCLRaw.bundle_e_sqlcipher | オープン ソースの非公式の SQLCipher ビルドを提供します。 |
SQLitePCLRaw.bundle_green | bundle_e_sqlite3 と同じですが、iOS の場合はシステム SQLite ライブラリが使用されます。 |
SQLitePCLRaw.bundle_sqlite3 | システム SQLite ライブラリが使用されます。 |
SQLitePCLRaw.bundle_winsqlite3 | Windows 10 のシステム SQLite ライブラリである winsqlite3.dll が使用されます。 |
SQLitePCLRaw.bundle_zetetic | Zetetic の公式の SQLCipher ビルドが使用されます (含まれていません)。 |
以下の C# サンプルコードを .NET6.0 コンソールアプリとしてプロジェクトを作成し実行した結果です。
using Microsoft.Data.Sqlite; using (var connection = new SqliteConnection("Data Source=sqlitedb.db")) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = @"CREATE TABLE winos(id INT, name VARCHAR(20))"; command.ExecuteNonQuery(); command.CommandText = @"INSERT INTO winos VALUES(1,'Windows10')"; command.ExecuteNonQuery(); command.CommandText = @"INSERT INTO winos VALUES(2,'Windows11')"; command.ExecuteNonQuery(); command.CommandText = @"SELECT name FROM winos"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { var name = reader.GetString(0); Console.WriteLine($"OSNAME: {name}"); } } }
実行したとき、SQLiteのデータベースファイルは実行ファイルと同じ場所に作成されます。
以上、.NET6.0, Microsoft.Data.SQLite を使って SQLite を操作する環境構築とサンプルコードでした。