今回は、複雑な SELECT 文に対応する select_custom 関数を追加して、簡単なテーブルでテストをしてシリーズ最後にします。
select_custom 関数は、引数 sql にパラメータ(%s)付きSQLステートメント、bind にパラメータの値リストを渡します。
class SimpleDB(object):
... (省略)...
def select_custom(self, sql, bind):
result = None
if self.__cursor is not None:
self.__cursor.execute(sql, bind)
columns = self.__cursor.description
result = []
for row in self.__cursor.fetchall():
item = {}
for (index, value) in enumerate(row):
item[columns[index][0]] = value
result.append(item)
return result
## End def select_custom
... (省略)...
## End class
次に、SimpleDBクラスで、テーブルへデータ登録、更新、削除、そして選択してテストします。
テーブル名は t_test でテーブル定義は以下です。
CREATE TABLE t_test (
id int NOT NULL AUTO_INCREMENT
,name varchar(260) NULL
,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
以下、テスト用コードです。
if __name__ == '__main__':
dbconfig = {
"host": "localhost",
"database": "<your database>",
"user": "<your username>",
"password": "<your secure password>"
}
try:
db = SimpleDB(dbconfig['host'], dbconfig['database'], dbconfig['user'], dbconfig['password'])
db.open()
# insert
data = { 'name' : '山田 太郎' }
rowid = db.insert("t_test", data)
print "rowid: %d" % rowid
# select
conditions = { 'id' : rowid }
res = db.select("t_test", conditions, "id", True)
if res is not None:
for r in res:
print "select : %s, %s" % (r['id'], r['name'])
# select_custom
bind = [ rowid ]
res = db.select_custom("select * from t_test where id = %s order by id", bind)
if res is not None:
for r in res:
print "select_custom : %s, %s" % (r['id'], r['name'])
# update
conditions = { 'id' : rowid }
data = { 'name' : '山田 花子' }
rows_affected = db.update("t_test", data, conditions)
print "%d 件更新" % rows_affected
# select all
conditions = None
res = db.select("t_test", conditions, "id", True)
if res is not None:
for r in res:
print "select : %s, %s" % (r['id'], r['name'])
# delete
conditions = { 'name' : '山田 花子' }
rows_affected = db.delete("t_test", conditions)
print "%d 件削除" % rows_affected
# select all
conditions = None
res = db.select("t_test", conditions)
if res is not None:
for r in res:
print "select : %s, %s" % (r['id'], r['name'])
db.close()
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print "%s, %s, %s" % (exc_type, fname, exc_tb.tb_lineno)
実行結果:
# python simpledb.py
rowid: 15
select : 15, 山田 太郎
select_custom : 15, 山田 太郎
1 件更新
select : 15, 山田 花子
1 件削除
参考までに:
SimpleDBクラスのソース: simpledb.py
(ファイル名を simpledb.py_.txt から “simpledb.py” に変更してください。)