Python操作SQLite介紹

Python操作SQLite介紹

 

Python自帶Sqlite3數據庫。要用Python操作SQLite,不用下載SQLite,只要先import sqlite3後,即可操作SQLite。

SQLite,是一款輕型的數據庫,是遵守ACID——原子性(Atomicity)、一致性(Consistency)、隔離性(Isolation)、持久性(Durability)的關係型數據庫管理系統。它佔用資源非常的低,因此,常作爲嵌入式數據庫。

 

Python操作SQLite數據庫步驟:

首先第一步是導入sqlite3模塊,sqlite3是一個與SQLite交互的庫;

import sqlite3

然後需要創建一個訪問數據庫的連接,比如我們創建一個測試用的數據庫,命名爲test.db;

conn = sqlite3.connect('./test.db')

現在我們就已經連接到數據庫了,然後需要創建遊標也就是Cursor;

cursorA = conn.cursor()

通過Cursor執行SQL語句,然後獲得執行結果,我們先來創建一個students表;

sql = 'create table students(id int primary key, name varchar(20) not null , age int not null)'

cursorA.execute(sql)  # 創建表的命令

最後一定要記得關閉遊標和關閉連接;

cursorA.close()

conn.close()

 

例1建立名爲test.db的數據庫,在其中建立students,代碼內容如下:

#引入sqlite3

import sqlite3

 

#打開數據庫連接,如果數據庫不存在,那麼它就會被創建,最後將返回一個數據庫對象。

conn = sqlite3.connect('test.db')

#創建操作的遊標

cursorA=conn.cursor()

#創建一個表students 首先判斷students這張表是否存在,如果不存在則新建——IF NOT EXISTS

cursorA.execute('''CREATE TABLE IF NOT EXISTS  students

       (ID INT PRIMARY KEY NOT NULL,

       NAME     TEXT  NOT NULL,

       AGE      INT   NOT NULL);''');

print("表創建成功");

#提交事務:

conn.commit()

print("-------------------");

 

#插入數據

cursorA.execute("INSERT INTO sTudents(ID,NAME,AGE) VALUES(1,'Allen',25)")

#cursorA.execute("INSERT INTO sTudents(ID,NAME,AGE) VALUES(2,'Maxsu',20)")

#cursorA.execute("INSERT INTO sTudents(ID,NAME,AGE) VALUES(3,'Teddy',24)")

 

#提交事務:

conn.commit()

 

print("記錄插入成功");

# 通過rowcount獲得插入的行數:

print('rowcount(一共插入的行數):', cursorA.rowcount)

print("-------------------");

 

#關閉Cursor:

cursorA.close()

#關閉連接

conn.close()

 

#讀取表students

#打開數據庫連接,如果數據庫不存在,那麼它就會被創建,最後將返回一個數據庫對象。

conn = sqlite3.connect('test.db')

#創建操作的遊標

cursorA=conn.cursor()

 

#執行查詢語句:

cursorA.execute("SELECT * from students")

#獲得查詢結果

values = cursorA.fetchall()

print(values)

 

#關閉Cursor:

cursorA.close()

#關閉連接

conn.close()

 

保存文件名爲testSqlite.py,運行結果:

 

 

SQLite數據庫中一個特殊的表叫 sqlite_master,sqlite_master的結構。

CREATE TABLE sqlite_master (

type TEXT,

name TEXT,

tbl_name TEXT,

rootpage INTEGER,

sql TEXT

);

我們可以通過查詢這個表來獲取數據庫所有的表名:

SELECT name FROM sqlite_master WHERE type='table' ORDER BY name

還可以通過:

PRAGMA  table_info(“表名”)

來獲取表結構。

 

例2、查看名爲test.db數據庫是否含有students,代碼內容如下:

 

#引入sqlite3

import sqlite3

try:

    #打開數據庫連接,如果數據庫不存在,那麼它就會被創建,最後將返回一個數據庫對象。

    conn = sqlite3.connect('test.db')

 

    #查看數據庫是否含有students表

    cursorA=conn.execute("SELECT name FROM sqlite_master WHERE type='table'");

 

    print("表名")

    print(cursorA.fetchall())

 

    #關閉連接

    conn.close()

except sqlite3.Error as e:

    print(e)

 

保存文件名爲Lookuptable.py,運行結果:

 

可以將上例中的print(cursorA.fetchall())改爲

for it in cursorA:

      for i in range(len(it)):

           print(it[i],)

      print('\n')

改後代碼如下:

#引入sqlite3

import sqlite3

try:

    #打開數據庫連接,如果數據庫不存在,那麼它就會被創建,最後將返回一個數據庫對象。

    conn = sqlite3.connect('test.db')

 

    #查看數據庫是否含有students表

    cursorA=conn.execute("SELECT name FROM sqlite_master WHERE type='table'");

 

    print("表名")

    #print(cursorA.fetchall())

    for it in cursorA:

      for i in range(len(it)):

           print(it[i],)

      print('\n')

 

    #關閉連接

    conn.close()

except sqlite3.Error as e:

    print(e)

 

運行結果:

就寫到這裏吧。

想深入學習可參考,可以參考菜鳥教程之SQLite - Python

https://www.runoob.com/sqlite/sqlite-python.html

 

還可以參看如下好的博文

python中sqlite3對數據庫的增刪改查

https://blog.csdn.net/liuyanlin610/article/details/76021959

淺談Python自帶數據庫SQLite3模塊的使用

https://blog.csdn.net/GuoQiZhang/article/details/91344509

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章