IoT+WEBのためのホームサーバ計画の実装編16。PythonでDBアクセス。
2020-03-14 2020-03-22
PythynでDBのアクセス
そういえば、前回は、簡単なテストをしただけだったので、
ちゃんと書いてみます。
前回はこれ。
完成形から
import sqlite3
from contextlib import closing
class hiraDB:
#---------------------------------------
#
#---------------------------------------
def __init__(self, dbname = 'test.db'):
self.dbname = dbname
self.conn = None
#---------------------------------------
# 前
#---------------------------------------
def __enter__(self):
#print("before(__enter__)")
return self
#---------------------------------------
# 後
#---------------------------------------
def __exit__(self, exc_type, exc_value, traceback):
if self.conn != None:
self.close()
#print("after(__exit__)")
#---------------------------------------
# open
#---------------------------------------
def open(self,dbname=None):
if dbname != None:
dn = dbname
else:
dn = self.dbname
try:
self.conn = sqlite3.connect(dn)
except Exception as e:
return False
return True
#---------------------------------------
def close(self):
self.conn.close()
#---------------------------------------
def commit(self):
self.conn.commit()
#---------------------------------------
def execSQL(self,sql,dat=None):
if self.conn == None:
return False
try:
c = self.conn.cursor()
if dat != None:
a = c.execute(sql,dat)
else:
a = c.execute(sql)
except Exception as e:
return False
return a
#---------------------------------------
def execSQLone(self,sql,dat=None):
a = self.execSQL(sql,dat)
b = a.fetchone()
return a,b
#---------------------------------------
def execSQLall(self,sql,dat=None):
a = self.execSQL(sql,dat)
b = a.fetchall()
return b
#---------------------------------------
#with hiraDB() as A:
if __name__ == '__main__':
with hiraDB() as A:
a = A.open("/?*a\\%4'")
print("ret:",a)
if a == False:
A.open()
#a = A.execSQLall('select * from T_user')
a,b = A.execSQLone('select * from T_user')
#a = A.execSQLone('select count(*) as hira from T_user')
print("-------")
print(b)
print(len(b))
print(b[2])
print("-------")
print(a.fetchone())
print(a.fetchone())
テスト結果
ret: False
-------
(1, 'hiraide', 'passMD', 0, 1583326080, 1583326080, None, None)
8
passMD
-------
(2, 'hiraide2', 'passMD', 0, 1583326153, 1583326153, None, None)
(3, 'hiraide3', 'passMD', 0, 1583326356, 1583326356, None, None)
特に難しいとかないから説明するとこ無いなぁ^^;