LoginSignup
5
2

More than 5 years have passed since last update.

ロボアプリ上でのデータ保存(2)

Last updated at Posted at 2017-05-31

 前回の投稿『ロボアプリ上でのデータ保存(1)』では、アプリフォルダのパスを取得しました。実際にファイルの書き込み・読み込みを行いたいと思います。
 汎用性が高いJSONとSQLiteを試したいと思います。

JSONでの読み書き

 書き込み側のボックス、読み込み側のボックスをそれぞれ用意します。ボックス変数として[JSON File]それぞれに追加します。テストデータがファイルとして保存され、読み込み側でファイルが読み込まれデータの受け渡しができていることが確認できます。

ボックスの構成

fig1.png
ボックス変数の構成:書き込み側(読み込み側は同様)
fig2.png

書き込み側

import json

# 書き込むJSONデータ
jsonData = {'test' : 'testValue'}

# アプリフォルダを取得する
appFolder = self.behaviorAbsolutePath().replace(self.behaviorRelativePath(), "")
# アプリフォルダを起点にして保存するJSON Fileのパスを確定する
writePath = appFolder + self.getParameter("JSON File")
self.logger.info('== json path: ' + writePath)

# JSON ファイルへの書き出しを行う
try:
    fsWrite = open(writePath, "w")
    json.dump(jsonData, fsWrite)
except Exception as e:
    self.logger.info('error: ' + e.message)
    self.onStopped()

self.onStopped()

読み込み側

import json

# 読み込むJSONデータ
jsonData = {}

# アプリフォルダを取得する
appFolder = self.behaviorAbsolutePath().replace(self.behaviorRelativePath(), "")
# アプリフォルダを起点にして読み込むJSON Fileのパスを確定する
readPath = appFolder + self.getParameter("JSON File")
self.logger.info('== json path: ' + readPath)

# JSON ファイルの読み込みを行う
try:
    # ファイルの存在を確認し実行
    if(os.path.exists(readPath)):
        fsRead = open(readPath, "r")
        jsonData = json.load(fsRead)
except Exception as e:
    self.logger.info('error: ' + e.message)
    self.onStopped()

# 読み込み内容をログに書き出す
self.logger.info('===> ' + str(jsonData))

self.onStopped()

SQLiteでの読み書き

 JSONの場合と同様に書き込み側のボックス、読み込み側のボックスをそれぞれ用意します。ボックス変数として[SQLite File]それぞれに追加します。テストデータがファイルとして保存され、読み込み側でファイルが読み込まれデータの受け渡しができていることが確認できます。

ボックスの構成

fig1.png
ボックス変数の構成:書き込み側(読み込み側は同様)
fig2.png

書き込み側

import sqlite3

# アプリフォルダを取得する
appFolder = self.behaviorAbsolutePath().replace(self.behaviorRelativePath(), "")
# アプリフォルダを起点にして保存するJSON Fileのパスを確定する
dbPath = appFolder + self.getParameter("SQLite File")
self.logger.info('== db path: ' + dbPath)

# SQLiteへの接続を行いクエリを実行する
try:
    # データベースに接続する
    conn = sqlite3.connect(dbPath)
    c = conn.cursor()

    # クエリを実行する
    # テーブルの存在を確認する
    sqlCheckTableExists = 'select count(*) from sqlite_master where type="table" and name="test";'
    result = c.execute(sqlCheckTableExists).fetchall()
    if(result[0][0] == 0):
        # テーブルを作成する
        self.logger.info('===> create table')
        sqlCreateTable = 'create table test (id int, key varchar(64), value varchar(128))'
        c.execute(sqlCreateTable)

    # データベースの結果を反映させる
    conn.commit()
    conn.close()
except Exception as e:
    self.logger.info('error: ' + e.message)
    self.onStopped()

self.onStopped()

読み込み側

import sqlite3

# アプリフォルダを取得する
appFolder = self.behaviorAbsolutePath().replace(self.behaviorRelativePath(), "")
# アプリフォルダを起点にして保存するJSON Fileのパスを確定する
dbPath = appFolder + self.getParameter("SQLite File")
self.logger.info('== db path: ' + dbPath)

# SQLiteへの接続を行いクエリを実行する
try:
    # データベースに接続する
    conn = sqlite3.connect(dbPath)
    c = conn.cursor()

    # クエリを実行する
    # テーブルの存在を確認する
    sqlCheckTableExists = 'select count(*) from sqlite_master where type="table" and name="test";'
    result = c.execute(sqlCheckTableExists).fetchall()
    if(result[0][0] == 0):
        self.logger.info('===> table not exists')
    else:
        # テーブルの内容を表示する
        self.logger.info('===> table exists')
        sqlSchemaShow = 'select * from sqlite_master where type="table" and name="test";'
        result = c.execute(sqlSchemaShow).fetchall()
        self.logger.info(str(result))

    # データベースの結果を反映させる
    conn.commit()
    conn.close()
except Exception as e:
    self.logger.info('error: ' + e.message)
    self.onStopped()

self.onStopped()

最後に

 JSONの場合も、SQLiteの場合も同じ手法でデータの読み書きができることがわかりました。
 ロボアプリをバージョンアップした場合これらのデータは必然的にリセットされてしまうことになります。バージョンアップの際は書き込みデータのバックアップ及び復元のプロセスが必要になりますね。

5
2
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
5
2