測試數據庫名稱Test
測試表格名稱Person
字段Id:類型uniqueidentifier,默認值:newId()
字段Name:類型nvarchar(500)
字段Photo:類型varbinary(MAX)數據庫
#導入QtSql模塊 from PyQt5.QtSql import QSqlDatabase, QSqlQuery from PyQt5.QtCore import QIODevice from PyQt5.QtGui import QImage #建立數據庫鏈接並打開(未指定數據庫名,建立默認鏈接) db = QSqlDatabase.addDatabase("QODBC") db.setDatabaseName("Driver={Sql Server};Server=localhost;Database=TEST;Uid=sa;Pwd=123456") db.open() #建立查詢對象(使用默認數據庫鏈接) query = QSqlQuery() #插入記錄並返回新記錄Id值 query.exec("INSERT INTO Person(Name) OUTPUT INSERTED.Id VALUES('Tom')") query.next() NewId = query.value("Id") #刪除記錄,使用"?"操做符綁定值 query.prepare("DELETE FROM Person WHERE Name=?") query.bindValue(0,"Tom") query.exec_() #此處調用exec_() #將圖片保存到數據庫,使用冒號佔位符 query.prepare("INSERT INTO Person(Name,Photo) VALUES(:N, :P)") imagebytes = QByteArray() buffer = QBuffer(imagebytes) buffer.open(QIODevice.WriteOnly) image = QImage(r"d:\test.jpg") image.save(buffer,"JPG") buffer.close() query.bindValue(":N","張三") query.bindValue(":P",imagebytes) query.exec_() #從數據庫載入圖片 query.prepare("SELECT Photo FROM Person WHERE Name=:Nm") query.bindValue(":Nm","張三") query.exec_() query.next() imagebytes = query.value("Photo") buffer = QBuffer(imagebytes) buffer.open(QIODevice.ReadOnly) image = QImage() image.load(buffer,"JPG") buffer.close()