PyQt5之SQLite數據庫操做(1)

鏈接數據庫

導入庫文件python

from PyQt5 import QtSql
from PyQt5.QtSql import QSqlQuery

QtSql類即QT中的QSqlDatabase類,用於處理與數據庫的鏈接

QSqlQuery類提供了執行和操做SQL語句打方法sql


第一步鏈接sqlite數據庫數據庫

database = QtSql.QSqlDatabase.addDatabase('QSQLITE')
database.setDatabaseName('test.db')
沒有test.db這個文件的時候則會在當前目錄新建一個test.db文件

打開數據庫,打開成功返回True函數

database.open()


新建表

創建一個名爲student的表,包含id,name,age三個屬性,其中ID爲主鍵

query.prepare('create table student (id int primary key, name varchar(30),age int)')
if not query.exec_():
    query.lastError()
else:
    print('create a table')

插入數據

addBindValue()將值添加到列表中,調用順序決定添加的順序
insert_sql = 'insert into student values (?,?,?)'
query.prepare(insert_sql)
query.addBindValue(4)
query.addBindValue('test3')
query.addBindValue(1)
if not query.exec_():
    print(query.lastError())
else:
    print('inserted')


查詢

查詢返回數據使用value(int)函數,例如select id,name,age from student   value(0)等於返回id屬性的值,value(2)等於age屬性

exec_()查詢成功返回true查詢 不然返回falsespa

query.prepare('select id,name,age from student')
if not query.exec_():
    query.lastError()
else:
    while query.next():
        id = query.value(0)
        name = query.value(1)
        age = query.value(2)
        print(id,name,age)

能夠經過record().indexOf(str)來獲取索引值,
code

if query.exec('select id ,name,age from student'):
    id_index = query.record().indexOf('id')
    name_index = query.record().indexOf('name')
    age_index = query.record().indexOf('age')
    while query.next():
        id = query.value(id_index)
        name = query.value(name_index)
        age = query.value(age_index)
        print(id, name, age)




一:使用exec()操做sqlite

指令執行成功則 exec_()會返回True並把查詢狀態設爲活躍狀態,不然返回false索引

另外對於SQLite,查詢字符串一次只能包含一條語句。若是給出多個語句,則函數返回false字符串

if query.exec('select id ,name,age from student'):
    while query.next():
        id = query.value(0)
        name = query.value(1)
        age = query.value(2)
        print(id, name, age)


二:execBatch()操做

這個函數是批處理以前準備好的指令,若是數據庫不支持批處理他會本身調用exec()來模擬it

query.prepare('insert into student values (?,?,?)')
query.addBindValue([6,7,8])
query.addBindValue(['test5','test6','test7'])
query.addBindValue([1,1,1])
if query.execBatch():
    print("inserted ")

三:executedQuery()返回最後一個執行成功的指令

if query.exec('select id ,name,age from student'):
    while query.next():
        id = query.value(0)
        name = query.value(1)
        age = query.value(2)
        print(id, name, age)
        
print(query.executedQuery())
執行結果爲:select id ,name,age from student


四: 其餘

finish()終止當前的操做

isActive()返回當前是否處於活躍狀態
isNull(int field)返回當前是否不活躍

isSelect()返回是否是一個查詢語句

next()檢索結果中的下一條記錄(若是可用),並將查詢放在檢索到的記錄上。請注意,結果必須處於活動狀態,而且在調用此函數以前,isSelect()必須返回true,不然它將不執行任何操做並返回false。


指令執行成功則 exec_()會返回True並把查詢狀態設爲活躍狀態,不然返回false
相關文章
相關標籤/搜索