1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import sqlite3
def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
class Demo(object):
def __init__(self): super(Demo, self).__init__() self.conn = sqlite3.connect('test.db')
def create(self): with self.conn: self.conn.execute('''CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);''' )
def insert(self): with self.conn: self.conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ VALUES (5, 'Paul', 32, 'California', 20000.00 )")
def select(self): self.conn.row_factory = dict_factory c = self.conn.cursor() c.execute("SELECT id, name, address, salary from COMPANY") print(c.fetchall()) print(c.fetchone()) return c.fetchall()
def update(self): with self.conn: self.conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")
def delete(self): with self.conn: self.conn.execute("DELETE from COMPANY where ID=2;")
def __del__(self): self.conn.close()
if __name__ == '__main__': obj = Demo() obj.select()
|