当前位置: 首页>>代码示例>>Python>>正文


Python QSqlDatabase.database方法代码示例

本文整理汇总了Python中PyQt4.QtSql.QSqlDatabase.database方法的典型用法代码示例。如果您正苦于以下问题:Python QSqlDatabase.database方法的具体用法?Python QSqlDatabase.database怎么用?Python QSqlDatabase.database使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.QtSql.QSqlDatabase的用法示例。


在下文中一共展示了QSqlDatabase.database方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: on_btnAdd_clicked

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def on_btnAdd_clicked(self):
     
                
        if not self.database.isOpen():
            if not self.database.open():
                raise UserWarning( u"No se pudo establecer la conexión con "\
                                   + "la base de datos" )
        try:
            mov = dlgmovimientosbancarios(self)
#            Rellenar el combobox de las CONCEPTOS


            if mov.conceptosModel.rowCount() == 0:
                raise UserWarning( u"No existen conceptos en la base de "\
                                   + "datos que justifiquen la elaboración de Notas de Crédito o Débito" )
            
            mov.exec_()
        except UserWarning as inst:
            QMessageBox.critical( self, qApp.organizationName(), unicode( inst ) )
            logging.error( unicode( inst ) )
            logging.error( mov.conceptosModel.query().lastError().text() )
#        except Exception as inst:
#            QMessageBox.critical( self, qApp.organizationName(),
#                                   "Hubo un problema al tratar de crear"\
#                                   + " el nuevo pago" )
#            logging.critical( unicode( inst ) )
#            logging.error( query.lastError().text() )
        finally:
            if QSqlDatabase.database().isOpen():
                QSqlDatabase.database().close()
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:32,代码来源:conciliacion.py

示例2: setData

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def setData( self, column, value ):
        value = value.toList()
        if column < 0:
            return False
        if column == 0:
            try:
                if not QSqlDatabase.database().isOpen():
                    if not QSqlDatabase.database().open():
                        raise Exception( "No se pudo conectar con la base de datos" )
                query = QSqlQuery()
                if not query.prepare( """
                UPDATE categorias SET nombre = :nombre
                WHERE idcategoria = %d 
                """ % self.itemData[1] ):
                    raise Exception( "No se pudo preparar la consulta para actualizar la categoria" )

                query.bindValue( ":nombre", value[column].toString().strip() )
                if not query.exec_():
                    raise Exception( "No se pudo actualizar la categoria" )

            except Exception as inst:
                logging.error( unicode( inst ) )
                return False
            self.itemData[column] = value[column]
        return True
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:27,代码来源:categoriesmodel.py

示例3: delCliRecord

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
 def delCliRecord(self):
     if not self.db.isOpen():
         self.statusbar.showMessage(
             "Database non aperto...",
             5000)
         return
     selrows = self.cItmSelModel.selectedRows()
     if not selrows:
         self.statusbar.showMessage(
             "No selected customers to delete...",
             5000)
         return
     if(QMessageBox.question(self, "Delete Customers",
             "Do you want to delete: {0} customer(s)?".format(len(selrows)),
             QMessageBox.Yes|QMessageBox.No) ==
             QMessageBox.No):
         return
     QSqlDatabase.database().transaction()
     query = QSqlQuery()
     query.prepare("DELETE FROM clienti WHERE id = :val")
     for i in selrows:
         if i.isValid():
             query.bindValue(":val", QVariant(i.data().toInt()[0]))
             query.exec_()
     QSqlDatabase.database().commit()
     self.cModel.select()
开发者ID:L0cutus,项目名称:Gestione-Clienti,代码行数:28,代码来源:clienti.py

示例4: delDettRecord

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
 def delDettRecord(self):
     if not self.db.isOpen():
         self.statusbar.showMessage(
             "Database non aperto...",
             5000)
         return
     selrows = self.sItmSelModel.selectedRows()
     if not selrows:
         self.statusbar.showMessage(
             "No articles selected to delete...",
             5000)
         return
     if(QMessageBox.question(self, "Cancellazione righe",
             "Vuoi cancellare: {0} righe?".format(len(selrows)),
             QMessageBox.Yes|QMessageBox.No) ==
             QMessageBox.No):
         return
     QSqlDatabase.database().transaction()
     query = QSqlQuery()
     query.prepare("DELETE FROM fattslave WHERE id = :val")
     for i in selrows:
         if i.isValid():
             query.bindValue(":val", QVariant(i.data().toInt()[0]))
             query.exec_()
     QSqlDatabase.database().commit()
     self.sModel.revertAll()
     self.mmUpdate()
开发者ID:L0cutus,项目名称:Gestione-Fatture,代码行数:29,代码来源:fatture.py

示例5: save

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def save( self ):
        """
        Slot documentation goes here.
        """
#        self.datosRecibo.lineasAbonos =self.abonoeditmodel.lines
#        self.datosRecibo.lineas = self.editmodel.lines
        self.datosRecibo.observaciones = self.txtobservaciones.toPlainText()
        if self.datosRecibo.valid( self ):
            if QMessageBox.question( self, qApp.organizationName(),
                                 u"¿Esta seguro que desea guardar el recibo?",
                                 QMessageBox.Yes | QMessageBox.No ) == QMessageBox.Yes:
                if not QSqlDatabase.database().isOpen():
                    QSqlDatabase.database().open()


                if self.datosRecibo.save():
                    QMessageBox.information( self,
                        qApp.organizationName() ,
                         u"""El documento se ha guardado con éxito""" )
                    self.editmodel = None
                    self.updateModels()
                    self.navigate( 'last' )
                    self.status = True
                else:
                    QMessageBox.critical( self,
                         qApp.organizationName(),
                         """Ha ocurrido un error al guardar el documento""" )

                if self.database.isOpen():
                    self.database.close()
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:32,代码来源:recibo.py

示例6: __init__

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def __init__( self, parent = None ):
        super( FrmAccounts, self ).__init__( parent )

        self.setupUi( self )
        self.user = user.LoggedUser

        QSqlDatabase.database().open()
#        self.accountsTree.setModel( AccountsModel( 1 ) )



        self.model = AccountsModel( 1 )

        self.filtermodel = TreeFilterProxyModel()
        self.filtermodel.setShowAllChildren( True )
        self.filtermodel.setSourceModel( self.model )
        self.filtermodel.setFilterKeyColumn( DESCRIPCION )
        self.filtermodel.setFilterCaseSensitivity( Qt.CaseInsensitive )

        self.accountsTree.setModel( self.filtermodel )

        self.accountsTree.setColumnHidden( IDCUENTA, True )
        self.accountsTree.setColumnHidden( HIJOS, True )
        self.accountsTree.setColumnHidden( PADRE, True )

        self.accountsTree.setColumnWidth( CODIGO, 240 )
        self.accountsTree.setColumnWidth( DESCRIPCION, 240 )
        self.accountsTree.expandAll()
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:30,代码来源:cuentas.py

示例7: updateModels

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def updateModels( self ):
        """
        Recargar todos los modelos
        """
        try:
            if not(QSqlDatabase.database().isOpen() or QSqlDatabase.database().open()):
                raise Exception( "No se pudo abrir la base" )

            self.navmodel.setQuery( """
            SELECT
                c.Fecha,
                b.descripcion as Banco,
                cb.ctabancaria,
                m.Simbolo,
                cc.Codigo,
                c.saldolibro,
                c.saldobanco,
                cb.idcuentacontable,
                c.iddocumento
                FROM conciliaciones c
                JOIN cuentasbancarias cb ON c.idcuentabancaria = cb.idcuentacontable
                JOIN bancos b ON b.idbanco = cb.idbanco
                JOIN tiposmoneda m ON m.idtipomoneda = cb.idtipomoneda
                JOIN cuentascontables cc ON cc.idcuenta = cb.idcuentacontable
                ORDER BY c.iddocumento
                ;
            """ )
#        Este objeto mapea una fila del modelo self.navproxymodel a los controles
            self.mapper.setSubmitPolicy( QDataWidgetMapper.ManualSubmit )
            self.mapper.setModel( self.navproxymodel )
            self.mapper.addMapping( self.txtbanco, BANCO )
            self.mapper.addMapping( self.txtmoneda, MONEDA )
            self.mapper.addMapping( self.txtcuentabanco, CUENTABANCO )
            self.mapper.addMapping( self.txtcuenta, CUENTA )


#        asignar los modelos a sus tablas
            self.tablenavigation.setModel( self.navproxymodel )
            self.tabledetails.setModel( self.detailsmodel )
            self.proxymodel.setSourceModel( self.detailsmodel )

            self.tablenavigation.setColumnHidden( SALDOBANCO, True )
            self.tablenavigation.setColumnHidden( SALDOLIBRO, True )
            self.tablenavigation.setColumnHidden( IDCUENTABANCO, True )
            self.tablenavigation.setColumnHidden( IDDOC, True )

            self._ocultar_columnas()

        except UserWarning as inst:
            logging.error( unicode( inst ) )
            QMessageBox.critical( self, qApp.organizationName(), unicode( inst ) )
        except Exception as inst:
            logging.critical( unicode( inst ) )
            QMessageBox.critical( self, qApp.organizationName(),
                u"Hubo un error al tratar de iniciar una nueva conciliación "\
                + "bancaria" )
        finally:
            if QSqlDatabase.database().isOpen():
                QSqlDatabase.database().close()
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:61,代码来源:conciliacion.py

示例8: cargarMarcas

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def cargarMarcas( self ):
        if not QSqlDatabase.database().isOpen():
            if not QSqlDatabase.database().open():
                raise Exception( "No se pudo abrir la base de datos" )

        self.brandsmodel.setQuery( """
        SELECT idmarca, nombre 
        FROM marcas
        """ )
        if  QSqlDatabase.database().isOpen():
            QSqlDatabase.database().close()
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:13,代码来源:articulos.py

示例9: setupModelData

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def setupModelData( self, parent ):
        try:
            if not QSqlDatabase.database().isOpen():
                if not QSqlDatabase.database().open():
                    raise Exception( "No se pudo conectar con la base"\
                                     + " de datos" )
            parents = [parent]
            query = """
             SELECT
                 p.nombre, 
                p.idcategoria,
                COUNT(h.idcategoria) as hijos 
            FROM categorias p
            LEFT JOIN categorias h ON p.idcategoria = h.padre
            WHERE p.padre IS NULL
            GROUP BY p.idcategoria    
            """
            query = QSqlQuery( query )
            if not query.exec_():
                raise Exception( "No se pudieron recuperar las categorias" )

            x = 0
            while query.next():
                parent = parents[-1]
                parent.insertChildren( x, 1, [query.value( 0 ).toString(),
                                               query.value( 1 ).toInt()[0]] )


                if query.value( 2 ) > 0:
                    y = 0
                    childquery = """
                    SELECT
                        p.nombre ,
                        p.idcategoria 
                    FROM categorias p
                    WHERE p.padre = %d 
                    """ % query.value( 1 ).toInt()[0]
                    childquery = QSqlQuery( childquery )
                    childquery.exec_()
                    while childquery.next():
                        parent.child( x ).insertChildren( y, 1, [
                                          childquery.value( 0 ).toString(),
                                          childquery.value( 1 ).toInt()[0]] )

                        y += 1
                x += 1
            return True
        except Exception as inst:
            logging.error( unicode( inst ) )
            return False
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:52,代码来源:categoriesmodel.py

示例10: data

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def data( self ):
        data = {}
        fila = self.tblCuenta.selectionModel().currentIndex().row()
        fecha = self.dtPicker.date()

        data['banco'] = self.filtermodel.index( fila, 0 ).data().toString()
        data['id_cuenta_contable'] = self.filtermodel.index( fila, 4 ).data().toInt()[0]
        data['codigo_cuenta_contable'] = self.filtermodel.index( fila, 3 ).data().toString()
        data['cuenta_bancaria'] = self.filtermodel.index( fila, 5 ).data().toString()
        data['fecha'] = QDate( fecha.year(), fecha.month(), fecha.daysInMonth() )
        data['moneda'] = self.filtermodel.index( fila, 2 ).data().toString()


        if not QSqlDatabase.database().isOpen() and not QSqlDatabase.open():
            raise Exception( QSqlDatabase.lastError() )

        query = QSqlQuery()
        if not query.exec_( "CALL spSaldoCuenta( %d, %s )" % ( 
                data['id_cuenta_contable'],
                QDate( data['fecha'].year(), data['fecha'].month(), data['fecha'].daysInMonth() ).toString( "yyyyMMdd" )
            )
        ):
            raise Exception( query.lastError().text() )

        query.first()

        data['saldo_inicial_libro'] = Decimal( query.value( 0 ).toString() )



        return data
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:33,代码来源:conciliacion.py

示例11: currentDatabase

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
 def currentDatabase(self):
     """
     Public method to get the current database.
     
     @return reference to the current database (QSqlDatabase)
     """
     return QSqlDatabase.database(self.__activeDb)
开发者ID:usc-bbdl,项目名称:R01_HSC_cadaver_system,代码行数:9,代码来源:SqlConnectionWidget.py

示例12: __init__

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def __init__( self, parent = None ):
        """
        @param parent: El formulario padre de este frm
        """
        super( FrmArticulos, self ).__init__( parent )
        self.setupUi( self )
        self.database = QSqlDatabase.database()

#        self.__status = True
        self.backmodel = ArticlesModel()
        self.filtermodel = QSortFilterProxyModel()
        self.filtermodel.setSourceModel( self.backmodel )
        self.filtermodel.setFilterCaseSensitivity( Qt.CaseInsensitive )

        self.update_models()
#        self.tableview.addActions( ( self.actionEdit, self.actionNew ) )
        self.tableview.setColumnHidden( 0, True )
        self.tableview.resizeColumnsToContents()
        self.setWindowTitle( "Catalogo de Articulos" )
        self.tableview.setEditTriggers( QAbstractItemView.AllEditTriggers )
        self.actionEdit.setVisible( True )
        self.actionSave.setVisible( False )
        self.actionCancel.setVisible( False )

        self.nuevoarticulo = None
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:27,代码来源:articulos.py

示例13: __init__

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def __init__( self, user, user2, sesion, parent = None ):
        super( FrmCierreCaja, self ).__init__( parent )
        self.setupUi( self )
        self.user = user
        self.user2 = user2
        self.db = QSqlDatabase.database()
        self.query = QSqlQuery( """
        SELECT 
            d.fechacreacion,
            c.idcaja,
            c.descripcion 
        FROM documentos d
        LEFT JOIN docpadrehijos dp ON dp.idpadre=d.iddocumento
        LEFT JOIN documentos hijo ON dp.idhijo=hijo.iddocumento AND hijo.idtipodoc=%d
        JOIN cajas c on d.idcaja=c.idcaja
        WHERE d.idtipodoc=%d and d.idusuario= %d 
        AND hijo.iddocumento IS  NULL 
        ORDER BY d.iddocumento DESC
        LIMIT 1;""" % ( constantes.IDAPERTURA, constantes.IDAPERTURA, user.uid ) )

        if not self.query.exec_():
            raise Exception( "No se pudo preparar la Query" )
        self.query.first()
        self.dtFechaTime.setDate( self.query.value( 0 ).toDate() )
        self.cboCaja.addItem( self.query.value( 2 ).toString() )
        self.txtUsuario.setText( self.user.user )
        self.txtUsuario.setReadOnly( True )
        self.dtFechaTime.setReadOnly( True )
        self.dtFechaTime.dateTime().toString( "yyyyMMddhhmmss" )
        self.sesion = sesion
开发者ID:armonge,项目名称:EsquipulasPy,代码行数:32,代码来源:cierrecaja.py

示例14: __init__

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
    def __init__( self ):
        '''
        Constructor
        '''
        super( tbFactura, self ).__init__(  )

# ESTABLECER LA INTERFAZ AL FORMULARIO
        self.setupUi(self)
# VALIDADOR DE MODO DE EDICION
        self.readOnly = True
        self.editmodel = None
#ESTABLECER LA FECHA INICIAL , (establecida al dia de mañana)
        self.categoriesview.headers = ["Descripcion", "Precio", "Unidades","Existencia","","",""]

# Crear el modelo para cargar catalogo de clientes
        self.clientesModel = QSqlQueryModel()
# Crear lista de autocompletado para el combo de clientes
        self.clienteCompleter = QCompleter()     
# Modelo que carga el catalogo de productos
        self.existenciaModel = QSqlQueryModel()

# Establecer todos los controles en modo de edicion
        self.setControls( False )
# Crear la conexion a la base de datos
        self.database = QSqlDatabase.database()

        
        
        self.vistaprevia = False
        
# Cargar los modelos del modo de edicion
        self.updateEditModels()
        self.parent = self.parent()
开发者ID:joseanm,项目名称:pyqt_billing,代码行数:35,代码来源:factura.py

示例15: refresh

# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import database [as 别名]
 def refresh(self):
     """
     Public slot to refresh the connection tree.
     """
     self.__connectionTree.clear()
     self.emit(SIGNAL("cleared()"))
     
     connectionNames = QSqlDatabase.connectionNames()
     
     foundActiveDb = False
     for name in connectionNames:
         root = QTreeWidgetItem(self.__connectionTree)
         db = QSqlDatabase.database(name, False)
         root.setText(0, self.__dbCaption(db))
         if name == self.__activeDb:
             foundActiveDb = True
             self.__setActive(root)
         if db.isOpen():
             tables = db.tables()
             for table in tables:
                 itm = QTreeWidgetItem(root)
                 itm.setText(0, table)
     
     if not foundActiveDb and connectionNames:
         self.__activeDb = connectionNames[0]
         self.__setActive(self.__connectionTree.topLevelItem(0))
开发者ID:usc-bbdl,项目名称:R01_HSC_cadaver_system,代码行数:28,代码来源:SqlConnectionWidget.py


注:本文中的PyQt4.QtSql.QSqlDatabase.database方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。