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 1 year has passed since last update.

.NET:SQLiteのサンプル

Last updated at Posted at 2023-10-07

前書き

  • 自分の勉強メモ

依存関係

  • System.Data.SQLite.Coreをインストール
    NuGetでインストールする。作成者:SQLite Development Team
    SQLiteCore.png

ソースのサンプル

テーブル作成
public void CreateTable()
{
    using (var connection = new SQLiteConnection(@"Data Source=C:\aaa\DB-SQLite\test.db"));
    connection.Open();
    _ExecuteNonQuery(connection, "DROP TABLE IF EXISTS TMyTable");
    _ExecuteNonQuery(connection, "CREATE TABLE IF NOT EXISTS TMyTable (......)");
}

protected void _ExecuteNonQuery(SQLiteConnection conn, string sql)
{
    using var command = conn.CreateCommand();
    command.CommandText = sql;
    command.ExecuteNonQuery();
}
重複であれば、スキップ
protected const string _sqlInsertTable_Cust = @"
    INSERT OR IGNORE INTO {0} (Name, Num) VALUES ('{1}', '{2}')
";
遅いであれば、TRANSACTIONを使う
_ExecuteNonQuery(connWorkDB, "BEGIN TRANSACTION");
_ExecuteNonQuery(connWorkDB, "COMMIT TRANSACTION");
2つのDB連携してSQL実行
// mainDBを接続する。
using var connWorkDB = new SQLiteConnection(_ConnStringWork());
connWorkDB.Open();
_ExecuteNonQuery(connWorkDB, "BEGIN TRANSACTION");

// 別DBをAttachし、名称(SaveDB)を付ける
using (SQLiteCommand cmd = connWorkDB.CreateCommand()) {
    cmd.CommandText = @"ATTACH [Save.db] AS SaveDB;";
    cmd.ExecuteNonQuery();
}

// sql文では、SaveDB/mainで、DBを区別
using (SQLiteCommand cmd = connWorkDB.CreateCommand()) {
    cmd.CommandText = "SaveDB.TName, main.TName.....";
    cmd.ExecuteNonQuery();
}
_ExecuteNonQuery(connWorkDB, "COMMIT TRANSACTION");
connWorkDB.Close();

DB内容確認

SQLiteUI.png

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?