Python進階2 - 數據庫編程: 使用SQLite進行數據庫編程

操作SQLite數據庫

使用python操作數據庫的流程:

  1. 通過connect()函數獲取到數據庫連接對象;
  2. 通過數據庫連接對象獲取到cursor游標對象;
  3. 使用cursor對象執行sql語句;
  4. 關閉游標對象
  5. 數據庫連接對象

0.SQLite的一些全局參數

import sqlite3
print("數據庫模塊的API版本號: ",sqlite3.apilevel)
print("數據庫模塊的線程安全等級: ",sqlite3.threadsafety)
print("當前使用的SQL語句參數風格: ",sqlite3.paramstyle)
數據庫模塊的API版本號:  2.0
數據庫模塊的線程安全等級:  1
當前使用的SQL語句參數風格:  qmark

1.創建數據表

SQLite支持的數據類型:

  1. interger(整型)
  2. real(浮點數)
  3. text(文本)
  4. blob(大二進制對象)
  5. null(空)

甚至直接忽略數據類型也是可以的

# 1,獲取到數據庫連接對象Connection
conn = sqlite3.connect('firstdb.db')
print(conn)
# 2,獲取Cursor 對象
c = conn.cursor()
print(c)
# 3,執行sql語句
c.execute('''create table user_tb(
    _id integer primary key autoincrement,
    name text,
    pass text,
    gender text)''')
c.execute('''create table order_tb(
    _id integer primary key autoincrement,
    item_name text,
    item_price real,
    item_number real,
    user_id integer,
    foreign key(user_id) references user_tb(_id))''')
# 4,關閉游標
c.close();
# 5,關閉數據連接
conn.close()
<sqlite3.Connection object at 0x000001AF8DE7AF10>
<sqlite3.Cursor object at 0x000001AF8DFE9500>

如何觀察創建好的數據庫與表,使用SQLite Expert工具

去如下網址下載工具(Personal是免費版)
http://www.sqliteexpert.com/download.html

安裝和系統的對應版本,我使用的是64位程序

打開已經存在的數據庫firstdb.db,就可以查看上面創建的所有數據庫信息了

2.插入數據

2.1 插入一條數據

cursor的execute()方法

參數1: sql語句
    
參數2: 參數
import sqlite3

conn = sqlite3.connect('firstdb.db')
c = conn.cursor()

c.execute('insert into user_tb values(null,?,?,?)',('馬云','密碼123','male'))
c.execute('insert into order_tb values(null,?,?,?,?)',('外賣','100.00','3',1))

conn.commit()
c.close()
conn.close()

2.2 插入多條數據

cursor的executemany()方法:

參數1: sql語句
    
參數2: 參數組成的元組
import sqlite3
conn = sqlite3.connect('firstdb.db')
cursor = conn.cursor()

cursor.executemany('insert into user_tb values(null,?,?,?)',(
    ('小白','123456','male'),
    ('小菜','123456','male'),
    ('菜鳥','123456','male')
))

conn.commit()
cursor.close()
conn.close()

3.執行查詢

3.1 獲取一條記錄

fetchone()

import sqlite3

conn = sqlite3.connect('firstdb.db')
c = conn.cursor()
c.execute('select * from user_tb')
for col in (c.description):
    print(col[0],end='\t')
while True:
    row = c.fetchone()
    if not row:
        break
    print()
    print(row)
    print(row[1] , '-->' , row[2])
c.close()
conn.close()
_id name    pass    gender  
(1, '馬云', '密碼123', 'male')
馬云 --> 密碼123

3.2 獲取多條記錄

fetchmany(n): n條符合查詢條件的記錄

fetchall(): 全部查詢記錄

import sqlite3
conn = sqlite3.connect('firstdb.db')
c = conn.cursor()

c.execute('select * from user_tb')

while True:
    rows = c.fetchmany(1)
    for r in rows:
        print(r)
        print(type(r))
    if not rows:
        break
c.close()
conn.close()
(1, '馬云', '密碼123', 'male')
<class 'tuple'>

4.事務控制

每天補充中

5.執行SQL腳本

6.創建自定義函數

7.創建聚集函數

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容