diff options
author | Hui Lan <lanhui@zjnu.edu.cn> | 2019-05-13 08:56:43 +0800 |
---|---|---|
committer | Hui Lan <lanhui@zjnu.edu.cn> | 2019-05-13 08:56:43 +0800 |
commit | a4d1530c4505ac07cf8553f256a929e782670010 (patch) | |
tree | 43498eb473427c915085859e879e065e4e90ba28 | |
parent | 9eade245938118b04f6da0ceb4312dadb724d35c (diff) |
LectureNotesOnPython.rst: 在inheritance那节加了数据库sqlite添加与搜索的例子
-rw-r--r-- | LectureNotesOnPython.rst | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/LectureNotesOnPython.rst b/LectureNotesOnPython.rst index 0b0c4f2..647835a 100644 --- a/LectureNotesOnPython.rst +++ b/LectureNotesOnPython.rst @@ -2039,6 +2039,68 @@ IS-A 。 一手牌是一副牌。 +用于数据库操作。以 SQLite 为例子。 + + +.. code:: python + + # Reference: Dusty Phillips. Python 3 Objected-oriented Programming Second Edition. Pages 326-328. + # Copyright (C) 2019 Hui Lan + + import sqlite3 + + class Sqlite3Template: + def __init__(self, db_fname): + self.db_fname = db_fname + + def connect(self, db_fname): + self.conn = sqlite3.connect(self.db_fname) + + def instructions(self, query_statement): + raise NotImplementedError() + + def operate(self): + self.results = self.conn.execute(self.query) # self.query is to be given in the child classes + self.conn.commit() + + def format_results(self): + raise NotImplementedError() + + def do(self): + self.connect(self.db_fname) + self.instructions(self.query) + self.operate() + + + class InsertQuery(Sqlite3Template): + def instructions(self, query): + self.query = query + + + class RiskQuery(Sqlite3Template): + def instructions(self, query): + self.query = query + + def format_results(self): + output = [] + for row in self.results.fetchall(): + output.append(', '.join([str(i) for i in row])) + return '\n'.join(output) + + + if __name__ == '__main__': + + #iq = InsertQuery('RiskDB.db') + #iq.instructions("INSERT INTO inspection Values ('FoodSupplies', 'RI2019051301', '2019-05-13', '{}')") + #iq.do() + #iq.instructions("INSERT INTO inspection Values ('CarSupplies', 'RI2019051302', '2019-05-13', '{[{\"risk_name\":\"elevator\"}]}')") + #iq.do() + + rq = RiskQuery('RiskDB.db') + rq.instructions("SELECT * FROM inspection WHERE inspection_serial_number LIKE 'RI20190513%'") + rq.do() + print(rq.format_results()) + web 应用程序 ```````````` |