Python中使用SQLite

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.