Search

2018/06/03

powershellでSQLiteの接続とかINSERTとか

下記のサイトを参考にSQLiteへの接続とか書いてみた。
PowerShell: Accessing SQLite databases
https://social.technet.microsoft.com/wiki/contents/articles/30562.powershell-accessing-sqlite-databases.aspx


OSはWindows10Home64bitを使用。
sqlite-netFx46-binary-x64-2015-1.0.108.0.zipを
ダウンロードして解答。
下記3つをps1と同じフォルダに配置。
SQLite.Interop.dll
System.Data.SQLite.dll
System.Data.SQLite.xml


TATSUO IKURA様の入門講座でSQLiteの命令を学習。
とてもわかりやすいです!
SQLite入門 
https://www.dbonline.jp/sqlite/


デバッグのためにGUIのDB操作ツールも用意。
でも、chromeの拡張でも操作できたはず。
PupSQLite
https://forest.watch.impress.co.jp/library/software/pupsqlite/


nullで表示しないのは下記を参考に。
パイプライン「| Out-Null」だけが遅い。
PowerShellでNull破棄する際に最も適したやり方を探る guitarrapc_tech様
http://tech.guitarrapc.com/entry/2013/03/12/080349
What's the better (cleaner) way to ignore output in PowerShell?


たぶん下記のような感じでできるはず。
確かめてない。

#### This software is public domain.
#Path
$pathOrg = "c:\db";
$pathModule = Join-Path $pathOrg "System.Data.SQLite.dll";
$pathDBFile = Join-Path $pathOrg "testfile.sqlite";
[void][System.Reflection.Assembly]::LoadFile( $pathModule );

#Connect
$con = New-Object System.Data.SQLite.SQLiteConnection;
$sql = New-Object System.Data.SQLite.SQLiteCommand;
$con.ConnectionString = "Data Source = $pathDBFile";
$con.Open();
$sql.Connection = $con;




#Making table
$sql.CommandText = "CREATE TABLE IF NOT EXISTS test ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, created_datetime TIMESTAMP DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')) )";
$null = $sql.ExecuteNonQuery();


#INSERT
$sql.CommandText = "INSERT INTO test (id, message) VALUES (@id, @message)"
$sql.Parameters.AddWithValue("@id", 100);
$sql.Parameters.AddWithValue("@message", "Hello. No proble.");
$null = $sql.ExecuteNonQuery()


#INSERT with Max id
$sql.CommandText = "SELECT MAX(id) FROM test";
$id_max = $sql.ExecuteScalar();
$sql.CommandText = "INSERT INTO test ( id, title ) values( @id, @message )";
$null = $sql.Parameters.AddWithValue("@id" , ($id_max+1) );
$null = $sql.Parameters.AddWithValue("@message" , "Here is message." );
$null = $sql.ExecuteNonQuery();


#Delete
$sql.CommandText = "DELETE FROM test WHERE id = @id"
$null = $sql.Parameters.AddWithValue("@id" , 100 );
$null = $sql.ExecuteNonQuery();


#Display values
$sql.CommandText = "SELECT * FROM test";
$adapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $sql;
$data = New-Object System.Data.DataSet;
$null = $adapter.Fill($data);
$data.tables.rows;


#Close
$sql.Dispose()
$con.Close()




検証しないで書いたコードならPublic domainにしたいけど
詳しい記述に仕方がわからない・・・。
「This software is public domain.」 って合ってるのかな?


0 件のコメント:

コメントを投稿