Sqlite3資料庫Python基礎操作

來源:互聯網
上載者:User

標籤:遊標   hal   key   python   close   sqlite資料庫   插入資料   建立   tps   

1.資料庫操作步驟

使用sqlite3需要匯入包sqlite3,資料庫在操作時需要先串連資料庫,然後建立遊標Cursor。

當程式運行完以後,需要先關閉遊標,然後再關閉資料庫。

(1)查詢操作

查詢操作的步驟為:1.使用SQL語句進行查詢,2.從fetchall中將查詢結果讀出

使用Cursor對象執行select語句時,通過featchall()可以拿到結果集。結果集是一個list,每個元素都是一個tuple,對應一行記錄。

範例程式碼如下

import sqlite3#匯入包conn=sqlite3.connect(‘sample_database‘)#串連到SQLite資料庫cursor=conn.cursor()#建立一個Cursorcursor.execute("select employee.firstname,employee.lastname from employee")#使用SQL語句對資料庫進行操作for row in cursor.fetchall():#從fetchall中讀取操作    print(row)cursor.close()#關閉Cursorconn.close()#關閉資料庫
(2)插入、刪除與更新操作

步驟為:1.使用SQL語句進行查詢,2.提交操作

import sqlite3conn=sqlite3.connect(‘sample_database‘)#串連到SQLite資料庫cursor=conn.cursor()#建立一個Cursorcursor.execute(‘create table user (id varchar(20) primary key, name varchar(20))‘)#用SQL語句建立一個表cursor.execute(‘insert into user (id, name) values (\‘1\‘, \‘Michael\‘)‘)#用SQL語句向表中插入資料print(cursor.rowcount)#顯示插入的函數cursor.close()#關閉Cursorconn.commit()#提交操作conn.close()#關閉資料庫

使用Cursor對象執行insert,update,delete語句時,執行結果由rowcount返回影響的行數,就可以拿到執行結果

參考資料

使用SQLite-廖雪峰:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001388320596292f925f46d56ef4c80a1c9d8e47e2d5711000

Sqlite3資料庫Python基礎操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.