====== CSVをSQLiteのテーブルにインポートする ====== [[:powershell|一つ上へ]] # SQLite の DLL を読み込み Add-Type -Path ".\System.Data.SQLite.dll" # SQLite データベースのパス $dbPath = ".\test.db" $connectionString = "Data Source=$dbPath;Version=3;" # 接続を開く $connection = New-Object System.Data.SQLite.SQLiteConnection($connectionString) $connection.Open() # テーブル作成(無ければ作る) $command = $connection.CreateCommand() $command.CommandText = @" CREATE TABLE IF NOT EXISTS people ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER ); "@ $command.ExecuteNonQuery() | Out-Null # CSV を読み込み $csvPath = ".\data.csv" $rows = Import-Csv -Path $csvPath # トランザクション開始(高速化) $transaction = $connection.BeginTransaction() foreach ($row in $rows) { $command = $connection.CreateCommand() $command.CommandText = "INSERT INTO people (id, name, age) VALUES (@id, @name, @age);" # パラメータに値をバインド $command.Parameters.Add((New-Object System.Data.SQLite.SQLiteParameter("@id", $row.id))) | Out-Null $command.Parameters.Add((New-Object System.Data.SQLite.SQLiteParameter("@name", $row.name))) | Out-Null $command.Parameters.Add((New-Object System.Data.SQLite.SQLiteParameter("@age", $row.age))) | Out-Null $command.ExecuteNonQuery() | Out-Null } # コミット $transaction.Commit() # 接続を閉じる $connection.Close() Write-Host "CSVデータをSQLiteにインポートしました。"