標籤:targe get ima nbsp where row app android wiki
參考原文
廖雪峰Python教程
使用SQLite
SQLite是一種嵌入式資料庫,它的資料庫就是一個檔案。由於SQLite本身是用C寫的,而且體積很小,所以經常被整合到各種應用程式中,甚至在IOS和Android的APP中都可以整合。
Python中內建了SQLite3,串連到資料庫後,需要開啟遊標Cursor,通過Cursor執行SQL語句,然後獲得執行結果,Python定義了一套操作資料庫的API介面,任何資料庫要串連到Python,只需要提供符合Python標準的資料庫驅動即可。試一下:
#匯入SQLite驅動:import sqlite3#串連到SQlite資料庫#資料庫檔案是test.db,不存在,則自動建立conn = sqlite3.connect(‘test.db‘)#建立一個cursor:cursor = conn.cursor()#執行一條SQL語句:建立user表cursor.execute(‘create table user(id varchar(20) primary key,name varchar(20))‘)#插入一條記錄:cursor.execute(‘insert into user (id, name) values (\‘1\‘, \‘Michael\‘)‘)#通過rowcount獲得插入的行數:print(cursor.rowcount) #reusult 1#關閉Cursor:cursor.close()#提交事務:conn.commit()#關閉connection:conn.close()
再試試查詢:
#匯入SQLite驅動:import sqlite3#串連到SQlite資料庫#資料庫檔案是test.db,不存在,則自動建立conn = sqlite3.connect(‘test.db‘)#建立一個cursor:cursor = conn.cursor()#執行查詢語句:cursor.execute(‘select *from user where id=?‘, (‘1‘,))#使用featchall獲得結果集(list)values = cursor.fetchall()print(values) #result:[(‘1‘, ‘Michael‘)]#關閉cursor#關閉conncursor.close()conn.close()
Tips:在Python中操作資料庫時,要先匯入資料庫對應的驅動,然後,通過Connection對象和Cursor對象操作資料。
要確保開啟的Connection對象和Cursor對象都正確地被關閉,否則,資源就會泄露。
Python中使用SQLite