从QSqlQuery返回列名

时间:2018-11-20 20:39:04

标签: python pyqt pyqt5

我正在尝试创建一个小程序,该程序应基于存储日期的sqlite表显示表视图。通过有效性后,单元格将显示红色,表示有效性已过期。我有一个方法“ get_date_diff”,该方法检索电子邮件和过期日期,并将它们存储在列表中,以便以后将它们用作要批量发送的邮件的变量,即:Email(var)具有证书(var)的日期已过期(var) 。我的// A "fake" prefix used for all the normalized entries. // Choose something that is not used by your real URLs. const NORMALIZED_PREFIX = '/__normalized/'; // A list of "files" whose URLs you want to normalize. const FILES_TO_NORMALIZE = [ 'icon.svg', // ...anything else... ]; function normalizeUrl(request) { // Convert the request.url string into a URL object, // so that we can get the pathname cleanly. const url = new URL(request.url); for (const file of FILES_TO_NORMALIZE) { if (pathname.endsWith(file)) { // If we have a match, then normalize the URL by using our // standard prefix along with the specific file name. url.pathname = NORMALIZED_PREFIX + file; return url.href; } } // Otherwise, just return the original request's URL. return request.url; } self.addEventListener('fetch', event => { // This is a naive cache-first strategy. Customize to suit your needs: // https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/ event.respondWith(async function() { const requestKey = normalizeRequestUrl(event.request); const cache = await caches.open('runtime-cache'); const cachedResponse = await caches.match(requestKey); // If there's a cached response, use it. if (cachedResponse) { return cachedResponse; } // Otherwise, get a response from the network for the original request. // Make sure you *don't* call fetch(requestKey), // since that URL doesn't exist on the server! const networkResponse = await fetch(event.request); // When you save the entry in the cache, use cache.put() // with requestKey as the first parameter. await cache.put(requestKey, networkResponse.clone()); return networkResponse; }()); }); 语句使我获得了过期日期以及iflistes_pilotes中的电子邮件,我需要在第三个列表中填充罪魁祸首证书:是在certificate1,certificate2列中,还是可能在列中?两者:

mail_pilotes

SAMPLE OF THE TABLE

tableview所基于的数据库:

def get_date_diff(self):
    '''method to retrieve from DB expired certificates '''
    query = QSqlQuery("SELECT pilot_1,certificate1,certificate2,pilot_mail FROM Pilots")
    liste_pilotes = []
    mail_pilotes = []
    #certificate_expired = [] needs to be filled
    append_new = liste_pilotes.append
    append_new_mail = mail_pilotes.append
    while query_time.next():
        pilot_1 = query.value(0)
        date1 = query.value(1)
        date2 = query.value(2)
        pilot_mail = query.value(3)
        alter_certif1 = datetime.strptime(date1,"%Y-%m-%d")
        alter_certif2 = datetime.strptime(date2,"%Y-%m-%d")
        if alter_date1  < datetime.now() or alter_date2 < datetime.now():
            append_new(pilot_1)
            append_new_mail(pilot_mail)
    return liste_pilotes,mail_pilotes

1 个答案:

答案 0 :(得分:1)

想法是通过将日期存储在列表中来获取日期并进行比较,如果该列表中至少有一项保存其他数据:

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import random
import string

def createConnection():
    db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName(':memory:')
    if not db.open():
        return False

    query = QtSql.QSqlQuery()
    query.exec_('''CREATE TABLE Pilots(
        id INTEGER PRIMARY KEY, 
        pilot_1 TEXT, 
        certificate1 TEXT, 
        certificate2 TEXT,
        certificate3 TEXT,
        pilot_mail TEXT
        )''')

    for i in range(100):
        query.prepare("insert into Pilots values (?, ?, ?, ?, ?, ?)")
        query.addBindValue(i)
        query.addBindValue("".join(random.sample(string.ascii_letters, 15)))
        for j in range(3):
            days = random.randint(-10*365, 10*365)
            query.addBindValue(QtCore.QDate.currentDate().addDays(days))
        query.addBindValue("".join(random.sample(string.ascii_letters, 4) + ["@mail.com"]))
        if not query.exec_():
            print("error: ", query.lastError().text())
    return True

class DateDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(DateDelegate, self).initStyleOption(option, index)
        t = QtCore.QDate.fromString(index.data(), "yyyy-MM-dd")
        if t < QtCore.QDate.currentDate():
            option.backgroundBrush = QtGui.QBrush(QtGui.QColor("red"))



class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        tableview = QtWidgets.QTableView()
        self.setCentralWidget(tableview)
        query = QtSql.QSqlQuery()
        query.exec_('''SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots''')
        model = QtSql.QSqlQueryModel(self)
        model.setQuery(query)
        tableview.setModel(model)
        for name in ('certificate1', 'certificate2'):
            ix = query.record().indexOf(name)
            delegate = DateDelegate(tableview)
            tableview.setItemDelegateForColumn(ix, delegate)
        print(self.get_date_diff())

    def get_date_diff(self):
        query = QtSql.QSqlQuery("SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots")
        rec = query.record()
        cols = [rec.indexOf(name) for name in  ("certificate1", "certificate2")]
        results = []
        while query.next():
            pilot_1 = query.value(rec.indexOf("pilot_1"))
            pilot_mail = query.value(rec.indexOf("pilot_mail"))
            dates = [QtCore.QDate.fromString(query.value(col), "yyyy-MM-dd") for col in cols]
            filter_columns = [col for col, date in zip(cols, dates) if date < QtCore.QDate.currentDate()]
            if filter_columns:
                v = [pilot_1, pilot_mail, filter_columns]
                results.append(v)
        return results

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    if not createConnection():
        sys.exit(-1)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())