第十四天 第十一章 SQLite3資料庫

2022-09-13 02:51:16 字數 2904 閱讀 2332

#

資料庫程式設計介面

#在python database api 2.0規範中,定義了python資料庫api介面的各個部分,如模組介面、連線物件、游標物件、型別和構造器以及

#db api的可選擴充套件以及可選的錯誤處理機制等

#資料庫連線物件:主要提供獲取資料庫游標物件和提交、回滾事務的方法,以及關閉資料庫連線。

#connect()函式獲取連線物件,有多個引數,具體使用哪個引數,取決於使用的資料庫型別

#dsn:資料來源名稱,給出該引數表示資料庫依賴

#user:使用者名稱

#password:使用者密碼

#host:主機名

#database:資料庫名稱

#連線物件的方法

#close():關閉資料庫連線

#commit():提交事務(用於維護資料庫的完整性)

#rollback():回滾事務

#cursor():獲取游標物件,運算元據庫,如執行dml操作,呼叫儲存過程等

#游標物件:用於指示抓取資料庫操作的上下文,主要提供執行sql語句、呼叫儲存過程、獲取查詢結果等方法。

#游標物件的屬性:1 description 資料庫列型別和值的描述資訊 2 rowcount 回返結果的行數統計資訊,如select,update,callproc等

#游標物件方法如下:

#callproc(procname,[,parameters]) 呼叫儲存過程,需要資料庫支援

#close() 關閉當前游標

#execute(operation[,parameters]) 執行資料庫操作,sql語句或者資料庫命令

#executemany (operation,seq_of_params) 用於批量操作,如批量更新

#fetchone() 獲取查詢結果集中的下一條記錄

#fetchmany(size) 獲取指定數量的記錄

#fetchall() 獲取結果集的所有所有記錄

#nextset() 跳至下乙個可用的結果集

#arraysize 指定使用fetchmany()獲取的行數,預設為1

#setinputsizes(sizes) 設定在呼叫execute*()方法時分配的記憶體區域大小

#setoutputsize(sizes) 設定列緩衝區大小,對大資料列(如longs和blobs)尤其有用

#***************==== 使用 sqlite ***************====

import

sqlite3

#連線資料庫檔案:mrsoft.db,如果該檔案不存在則會自動建立

conn = sqlite3.connect('

mrsoft.db')

#建立乙個cursor游標物件

cursor =conn.cursor()

try:

#執行一條sql語句,建立user表,表內建立2個字段,自增序號:id和文字:name

cursor.execute('

create table user (id int(10) primary key, name varchar(20))')

#再次執行本程式,此處會報錯,因為資料庫中已經有了user這個表,不能重複建立

except

:

print('

表已經存在,不能重複建立')

## insert into 表名(欄位1,欄位2。。。) values(值1,值2。。。)

#cursor.execute('insert into user(id,name) values(1,"mrsoft")')

#cursor.execute('insert into user(id,name) values(2,"zac")')

#cursor.execute('insert into user(id,name) values(3,"loveyou")')

#select 欄位1,欄位2。。。 from 表名 where 查詢條件

cursor.execute('

select * from user')

#sqltext = cursor.fetchall()

#print(sqltext)

#sqltext = cursor.fetchmany(2)

#print(sqltext)

#sqltext = cursor.fetchone()

#print(sqltext)

## 使用點位符和元組的方式可以避免sql注入的風險,推薦使用這種方式

#cursor.execute('select * from user where id > ?',(1,))

#sqltext = cursor.fetchall()

#print(sqltext)

## 修改資料庫使用者資訊

#cursor.execute('update user set name = ? where id > ?',('zack_love',1))

#cursor.execute('select * from user')

#sqltext = cursor.fetchall()

#print(sqltext)

#刪除使用者資料資訊

cursor.execute('

delete from user where id = ?

',(2,))

cursor.execute(

'select * from user')

sqltext =cursor.fetchall()

print

(sqltext)

#關閉游標

cursor.close()

#提交事務

conn.commit()

#關閉資料庫

conn.close()

第十四天 Session

session通過sessionid來區分不同的客戶,session是以cookie或url重寫為基礎的,預設使用cookie來實現,系統會創造乙個名為jsessionid的輸出cookie,這稱之為session cookie,以區別persistent cookies 通常看不到jsession...

第十四天 response

教學導航 教學目標 案例二 生成驗證碼 了解 教學方法 我們在建立servlet時會覆蓋service 方法,或doget dopost 這些方法都有兩個引數,乙個為代表請求的request和代表響應response。service方法中的response的型別是servletresponse,而d...

Qt第十四天

qfiledialog檔案對話方塊 qcolordialog顏色對話方塊 qfontdialog字型對話方塊 qinputdialog輸入對話方塊 qmessagebox訊息框 dialog.h ifndef dialog h define dialog h include namespace ui...