conn = sqlite3.connect('enterprise.db') curs = conn.cursor() curs.execute('SELECT critter FROM zoo WHERE damages BETWEEN 0 AND 1000') print(curs.fetchall()) curs.close() conn.close()
輸出結果
1
[('duck',), ('bear',)]
DB2
1 2 3 4 5 6 7
conn = ibm_db.connect('DATABASE=enterprise;HOSTNAME=ip;PORT=50000;PROTOCOL=TCPIP;UID=user;PWD=pwd', '', '') stmt = ibm_db.exec_immediate(conn, 'SELECT critter FROM zoo WHERE damages BETWEEN 0 AND 1000') result = ibm_db.fetch_assoc(stmt) # 只有第一筆 while result != False: for index, item inenumerate(result.keys()): print(item) result = ibm_db.fetch_assoc(stmt) # 取下一筆
conn = sqlite3.connect('database.db') curs = conn.cursor() curs.execute("SELECT name FROM sqlite_master WHERE type='table';") print(curs.fetchall())
轉換 Table 資料為 dict
1 2 3 4 5 6 7 8 9 10
defdict_factory(cursor, row): """轉換tuple為dict""" returndict((col[0], row[idx]) for idx, col inenumerate(cursor.description))
conn = sqlite3.connect('database.db') curs = conn.cursor() curs.execute("SELECT * FROM Product") result = [dict_factory(curs, item) for item in curs.fetchall()] curs.close() conn.close()