PowerShellのスクリプトからsqliteデータベースの操作を行います。実行には sqlite3Win.dll を使用します。 sqlite3Win.dll は、Windows10, Windows11 に実装されている winsqlite3.dll を使用(コール)して sqlite の操作を行います。
sqlite3Win.dll の ダウンロード
こちら から sqlite3Win.7z のダウンロードを行い解凍します。
プログラム例
下記実行例の sqlite3WinTest.ps1 と sqlite3Win.dll を同じフォルダに入れ実行して下さい。
# sqlite3WinTest.ps1
Set-StrictMode -Version latest
Add-Type -Path ($PSScriptRoot + "/sqlite3Win.dll")
# SQL実行
function execSQL([string]$ssqla){
$ir = $sqlite3d.exec($ssqla)
if ($ir -ne 0){
$sms = $sqlite3d.errmes() + "`r`n[" + $ssqla + "]"
Write-Host $sms
}
return $ir
}
$sqlite3d = New-Object sqlite3Win.Sqlite3
$sdbfname = $PSScriptRoot + "\dbテスト.db" # データベースファイル名
$ir = $sqlite3d.open($sdbfname)
if ($ir -ne 0){
Write-Host "openエラー"
exit
}
$sSQL = "CREATE TABLE IF NOT EXISTS tbl3(" +
"id int primary key," +
"idtTime int," + # 日付時刻 : DateTime の ticks
"cnote text)"
$ir = execSQL $sSQL
$sSQL = "SELECT max(id) FROM tbl3"
$ir = execSQL $sSQL
$id = 0
if ($sqlite3d.columnData(0, 0) -ne $null -and !$sqlite3d.columnData(0, 0).Equals([string]::Empty)){
$id = [int]$sqlite3d.columnData(0, 0)
}
$id++
$sSQL = "INSERT INTO tbl3 VALUES (" + $id.ToString() + "," + [DateTime]::Now.Ticks.ToString() + ",'漢字123abcDEFカタカナ')"
$ir = execSQL $sSQL
$sSQL = "SELECT id, idtTime, cnote FROM tbl3 ORDER BY id DESC LIMIT 5"
$ir = execSQL $sSQL
$irec = $sqlite3d.recordCount # レコード数
$icol = $sqlite3d.columnCount # 項目数
$sa = ""
for($ix = 0; $ix -lt $icol; $ix++){
$sa += $sqlite3d.columnName($ix) + ","
}
Write-Host $sa # カラム(項目)名
for($iy = 0; $iy -lt $irec; $iy++){
$sa = $sqlite3d.columnData($iy, 0) + ","
$la = [long]$sqlite3d.columnData($iy, 1)
$sa += ([DateTime]::FromBinary($la)).ToString() + "," # ticks->DateTime型
$sa += $sqlite3d.columnData($iy, 2)
Write-Host $sa # 取得データ
}
$ir = $sqlite3d.close()
日付時刻は、DateTime オブジェクトの ticks 値を使用しています。
インデックスの作成
CREATE INDEX IF NOT EXISTS インデックス名 ON テーブル名(カラム名1, カラム名2, .......)
インデックスの削除
DROP INDEX インデックス名
UPDATE テーブル名 SET カラム名1=値1, カラム名2=値2, ..... WHERE 条件式
UPDATE テーブル名 SET (カラム名1, カラム名2, .......) = (値1, 値2, .......) WHERE 条件式
すべてのカラムに値をセット
INSERT INTO テーブル名 VALUES (値1, 値2, .......)
カラムを指定して値をセット
INSERT INTO テーブル名 (カラム名1, カラム名2, .......) VALUES (値1, 値2, .......)
sqlite3Win.dll は、弊社作成の.NET用のdllで Windows10、windows11の winsqlite3.dll を使用(コール)しています。sqlite3Win.dll の実行には、.NET Framework 4.5 が必要です。32ビット、64ビット版があり、C# でも使用可能です。
関数名 | 説明 |
---|---|
open | データベースファイルを開きます。 |
close | データベースファイルを閉じます。 |
exec | SQLを実行します。 |
columnData | SQL実行後のデータを取得します。 |
columnName | SQL実行後の項目名を取得します。 |
errmes | エラーメッセージを取得します。 |
libversion | winsqlite3.dll のバージョン情報を取得します。 |
getVersion | sqlite3Win.dll のバージョン情報を取得します。 |
名称 | 説明 |
---|---|
recordCount | SQL実行後データのレコード数 |
columnCount | SQL実行後データの項目数 |