つづき
5.検索
データベースのメリットは、検索機能が充実している事である。
(1)ロシア軍の指揮官を検索した例
(2)指揮官で名前がBagで始まる人を検索した例
(3)歩兵でランドヴェーア(LW)を検索した例
6.その他
(1)補足
・データベースの主キーとして、国、(年+戦い名称)、名称の3ケ複合とした。
主キー(下図の鍵マークが付いている)が重複したデータは、ちゃんとエラーにしてくれるので、分かり易い。
・データの型は全て文字列型にした。射撃値、白兵戦値、士気値、射程などは
整数型の方が普通であるが、2文字の文字列型(2バイト)にした方がデータ容量の
節約(標準の整数型は4バイト)と拡張性が良いと考えた。
拡張性としては、射撃値にSkの文字が入る場合(ロシア軍竜騎兵)があり、
整数型だと困る。
・使う可能性が低い表画像名やデッキ名などは、外そうかとも考えたが、
膨大なデータになる訳でもないので、基本情報そのままとした。
(2)DBを検索・更新・削除・挿入するプログラム
プログラムソースを下記に示す。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
db=mysql.connector.connect(host="localhost", user="root", password="") | |
cursor=db.cursor() | |
cursor.execute("USE bataille") | |
db.commit() | |
# データを検索・取得 | |
cursor.execute('SELECT * FROM unit_info WHERE nation="France" and type="4inf" and backimage LIKE "%_g%" ') | |
rows = cursor.fetchall() | |
# 出力 | |
print(len(rows)) | |
for i in rows: | |
print(i) | |
cursor.close() | |
db.close() # ( )を忘れると、DBに接続したままになる。プロセスがスリープして、次のDBアクセスの邪魔になる。 | |
#抽出方法 | |
#戦列歩兵 | |
#cursor.execute('SELECT * FROM unit_info WHERE nation="Russia" and type="4inf" and backimage="" ') | |
# | |
#軽歩兵 | |
#cursor.execute('SELECT * FROM unit_info WHERE nation="Russia" and type="4inf" and backimage<>"" ') | |
# | |
#騎兵(射撃可能):主にユサールなど軽騎兵 | |
#cursor.execute('SELECT * FROM unit_info WHERE nation="Russia" and type="3cav" and fire<>"" ') | |
# | |
#騎兵(射撃不可能):主に胸甲騎兵など重騎兵 | |
#cursor.execute('SELECT * FROM unit_info WHERE nation="Russia" and type="3cav" and fire="" ') | |
# | |
#槍騎兵 | |
#cursor.execute('SELECT * FROM unit_info WHERE nation="Russia" and type="3cav" and firerange<>"" ') | |
# | |
#砲兵 | |
#cursor.execute('SELECT * FROM unit_info WHERE nation="Russia" and type="2art" ') | |
# | |
#指揮官 | |
#cursor.execute('SELECT * FROM unit_info WHERE nation="Russia" and type="1cmd" ') | |
# | |
#あいまい検索 | |
#cursor.execute('SELECT * FROM unit_info WHERE type="4inf" and name LIKE "%LW%" ') | |
# データを更新 | |
cursor.execute('UPDATE unit_info SET frontimage="A125" WHERE type="1cmd" and name LIKE "Dedo%" ') | |
db.commit() | |
# データを削除 | |
cursor.execute('DELETE FROM unit_info WHERE nation="France" and type="4inf" and name="21Fu Chasseur" ') | |
db.commit() | |
# データを挿入 | |
cursor.execute('INSERT INTO unit_info VALUES ("France", "1809Wagram", "1/Fu Chasseur", "8", "24", "14", "2", "6", "FG06", "SKE_g", "French0_2", "4inf") ') | |
db.commit() |
<個人的な感想>
SQLは上記の5.(2)(3)のように”あいまい検索”ができるので、とても便利である。
苦労して登録するからには、メリットがないと意味がない。