本文整理汇总了Python中PyQt4.QtSql.QSqlDatabase.open方法的典型用法代码示例。如果您正苦于以下问题:Python QSqlDatabase.open方法的具体用法?Python QSqlDatabase.open怎么用?Python QSqlDatabase.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtSql.QSqlDatabase
的用法示例。
在下文中一共展示了QSqlDatabase.open方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initDb
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def initDb():
"""open the db, create or update it if needed.
Returns a dbHandle."""
dbhandle = QSqlDatabase("QSQLITE")
if InternalParameters.isServer:
name = 'kajonggserver.db'
else:
name = 'kajongg.db'
dbpath = InternalParameters.dbPath or appdataDir() + name
dbhandle.setDatabaseName(dbpath)
dbExisted = os.path.exists(dbpath)
if Debug.sql:
logDebug('%s database %s' % \
('using' if dbExisted else 'creating', dbpath))
# timeout in msec:
dbhandle.setConnectOptions("QSQLITE_BUSY_TIMEOUT=2000")
if not dbhandle.open():
logError('%s %s' % (str(dbhandle.lastError().text()), dbpath))
sys.exit(1)
with Transaction(dbhandle=dbhandle):
if not dbExisted:
Query.createTables(dbhandle)
else:
Query.upgradeDb(dbhandle)
generateDbIdent(dbhandle)
return dbhandle
示例2: data
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [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
示例3: makeValueRelationDict
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def makeValueRelationDict(self, valueDict):
ret = dict()
codes = valueDict['FilterExpression'].replace('code in (', '').replace(')','').split(',')
keyColumn = valueDict['Key']
valueColumn = valueDict['Value']
table = valueDict['Layer'][:-17]#removing the date-time characters
uri = QgsDataSourceURI(self.currLayer.dataProvider().dataSourceUri())
if uri.host() == '':
db = QSqlDatabase('QSQLITE')
db.setDatabaseName(uri.database())
else:
db = QSqlDatabase('QPSQL')
db.setHostName(uri.host())
db.setPort(int(uri.port()))
db.setDatabaseName(uri.database())
db.setUserName(uri.username())
db.setPassword(uri.password())
if not db.open():
db.close()
return ret
in_clause = ','.join(map(str, codes))
query = QSqlQuery('select code, code_name from dominios.%s where code in (%s)' % (table, in_clause), db)
while query.next():
code = str(query.value(0))
code_name = query.value(1)
ret[code_name] = code
db.close()
return ret
示例4: getEDGVDbsFromServer
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def getEDGVDbsFromServer(self):
#Can only be used in postgres database.
try:
self.checkAndOpenDb()
except:
return []
query = QSqlQuery(self.gen.getDatabasesFromServer(),self.db)
dbList = []
while query.next():
dbList.append(query.value(0))
edvgDbList = []
for database in dbList:
db = None
db = QSqlDatabase("QPSQL")
db.setDatabaseName(database)
db.setHostName(self.db.hostName())
db.setPort(self.db.port())
db.setUserName(self.db.userName())
db.setPassword(self.db.password())
if not db.open():
QgsMessageLog.logMessage('DB :'+database+'| msg: '+db.lastError().databaseText(), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
query2 = QSqlQuery(db)
if query2.exec_(self.gen.getEDGVVersion()):
while query2.next():
version = query2.value(0)
if version:
edvgDbList.append((database,version))
else:
QgsMessageLog.logMessage(self.tr('Problem accessing database: ') +database+'\n'+query2.lastError().text(), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
return edvgDbList
示例5: __init__
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def __init__(self, netmanager, clipboard, parent = None):
super(MainWin, self).__init__(parent)
self.setWindowTitle("Eilat Browser " + netmanager.name)
self.netmanager = netmanager
self.clipboard = clipboard
self.tab_widget = QTabWidget(self)
self.tab_widget.tabBar().setMovable(True)
self.setCentralWidget(self.tab_widget)
self.tab_widget.setTabsClosable(True)
database = QSqlDatabase("QPSQL")
database.open("pguser", "pguser")
query = QSqlQuery(
"select concat(host, path) h, count(*) c from reply " +
"where status between 200 and 399 " +
"and is_bookmarkable(path) " +
"and host not in (select host from filtro) " +
"group by h " +
"order by c desc", database)
self.model = QSqlQueryModel()
self.model.setQuery(query)
self.tab_widget.tabCloseRequested.connect(self.del_tab)
def new_tab_from_clipboard():
""" One-use callback for QShortcut.
Reads the content of the PRIMARY clipboard and navigates to it
on a new tab.
"""
url = unicode(self.clipboard.text(QClipboard.Selection)).strip()
self.add_tab(url)
set_shortcuts([
("Ctrl+T", self, self.add_tab),
("Y", self, new_tab_from_clipboard),
("Ctrl+W", self, self.del_tab),
("N", self, partial(self.inc_tab, -1)),
("Ctrl+PgUp", self, partial(self.inc_tab, -1)),
("M", self, self.inc_tab),
("Ctrl+PgDown", self, self.inc_tab),
("Ctrl+Q", self, QApplication.closeAllWindows)
])
示例6: getDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def getDatabase(self, database = 'postgres'):
(host, port, user, password) = self.getServerConfiguration(self.serversCombo.currentText())
db = QSqlDatabase("QPSQL")
db.setDatabaseName(database)
db.setHostName(host)
db.setPort(int(port))
db.setUserName(user)
db.setPassword(password)
if not db.open():
QgsMessageLog.logMessage(db.lastError().text(), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
return db
示例7: dropDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def dropDatabase(self,db):
host = db.hostName()
port = db.port()
user = db.userName()
password = db.password()
database = 'postgres'
pgDB = QSqlDatabase('QPSQL')
pgDB.setHostName(host)
pgDB.setPort(port)
pgDB.setUserName(user)
pgDB.setPassword(password)
pgDB.setDatabaseName(database)
if not pgDB.open():
return False
sql = self.gen.dropDatabase(db.databaseName())
query = QSqlQuery(pgDB)
return query.exec_(sql)
示例8: save
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def save( self ):
"""
Guardar el nuevo articulo en la base de datos
"""
query = QSqlQuery()
result = False
try:
if not QSqlDatabase.database().isOpen():
if not QSqlDatabase.open():
raise UserWarning( u"No se pudo conectar con la"\
+ " base de datos" )
query.prepare( """
CALL spAgregarArticulos(
:activo,
:marca,
:subcategoria,
:dai,
:isc,
:comision,
:ganancia
)
""" )
query.bindValue( ":activo", 1 )
query.bindValue( ":marca", self.brand_id )
query.bindValue( ":subcategoria", self.cat_id )
query.bindValue( ":dai", str( self.dai ) )
query.bindValue( ":isc", str( self.isc ) )
query.bindValue( ":comision", str( self.comission ) )
query.bindValue( ":ganancia", str( self.profit ) )
if not query.exec_():
raise Exception( "No se pudo ejecutar la consulta" )
result = True
except UserWarning as inst:
logging.error( query.lastError().text() )
logging.error( unicode( inst ) )
except Exception as inst:
logging.critical( query.lastError().text() )
logging.critical( unicode( inst ) )
return result
示例9: getDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def getDatabase(self, database = 'postgres'):
(host, port, user, password) = self.getServerConfiguration(self.serversCombo.currentText())
db = QSqlDatabase("QPSQL")
db.setConnectOptions('connect_timeout=10')
db.setDatabaseName(database)
db.setHostName(host)
db.setPort(int(port))
db.setUserName(user)
if password == '':
conInfo = 'host='+host+' port='+port+' dbname='+database
self.setCredentials(db, conInfo, user)
else:
db.setPassword(password)
if not db.open():
QgsMessageLog.logMessage(db.lastError().text(), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
return db
示例10: makeValueRelationDict
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def makeValueRelationDict(self, valueDict):
"""
Gets the value relation dictionary. This is necessary for multi valued attributes.
"""
ret = dict()
codes = valueDict['FilterExpression'].replace('code in (', '').replace(')','').split(',')
in_clause = ','.join(map(str, codes))
keyColumn = valueDict['Key']
valueColumn = valueDict['Value']
table = valueDict['Layer'][:-17]#removing the date-time characters
uri = QgsDataSourceURI(self.currLayer.dataProvider().dataSourceUri())
if uri.host() == '':
db = QSqlDatabase('QSQLITE')
db.setDatabaseName(uri.database())
sql = 'select code, code_name from dominios_%s where code in (%s)' % (table, in_clause)
else:
db = QSqlDatabase('QPSQL')
db.setHostName(uri.host())
db.setPort(int(uri.port()))
db.setDatabaseName(uri.database())
db.setUserName(uri.username())
db.setPassword(uri.password())
sql = 'select code, code_name from dominios.%s where code in (%s)' % (table, in_clause)
if not db.open():
db.close()
return ret
query = QSqlQuery(sql, db)
if not query.isActive():
QMessageBox.critical(self.iface.mainWindow(), self.tr("Error!"), self.tr("Problem obtaining domain values: ")+query.lastError().text())
return ret
while query.next():
code = str(query.value(0))
code_name = query.value(1)
ret[code_name] = code
db.close()
return ret
示例11: dropDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def dropDatabase(self,db):
"""
Drops the created database case a problem occurs during database creation
db: QSqlDatabase to be dropped
"""
host = db.hostName()
port = db.port()
user = db.userName()
password = db.password()
database = 'postgres'
pgDB = QSqlDatabase('QPSQL')
pgDB.setHostName(host)
pgDB.setPort(port)
pgDB.setUserName(user)
pgDB.setPassword(password)
pgDB.setDatabaseName(database)
if not pgDB.open():
return False
sql = self.gen.dropDatabase(db.databaseName())
query = QSqlQuery(pgDB)
return query.exec_(sql)
示例12: getConnection
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
def getConnection(self, conndb, connhost, connport, connuser, connpass):
"""
Get a QSqlDatabase for a specific set of connection parameters
"""
db = None
db = QSqlDatabase("QPSQL")
db.setDatabaseName(conndb)
db.setHostName(connhost)
db.setPort(int(connport))
db.setUserName(connuser)
if not connpass or connpass == '':
conInfo = 'host='+connhost+' port='+connport+' dbname='+conndb
self.setCredentials(db, conInfo, connuser)
else:
db.setPassword(connpass)
if not db.open():
QMessageBox.critical(self, self.tr("Critical!"), self.tr('Database connection problem: \n') + db.lastError().text())
return db
示例13: ComplexWindow
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
class ComplexWindow(QtGui.QDockWidget, FORM_CLASS):
def __init__(self, iface, parent=None):
"""Constructor."""
super(ComplexWindow, self).__init__(parent)
# Set up the user interface from Designer.
# After setupUI you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)
#self.enderecoLine.setText('186.228.51.52')
#self.portaLine.setText('2101'
self.iface = iface
QObject.connect(self.dbButton, SIGNAL(("clicked()")), self.getDataSources)
QObject.connect(self.dbCombo, SIGNAL("activated(int)"), self.updateComplexClass)
QObject.connect(self.complexCombo, SIGNAL("activated(int)"), self.loadAssociatedFeatures)
QObject.connect(self.iface, SIGNAL("newProjectCreated()"), self.clearDock)
self.db = None
self.databases = None
self.factory = SqlGeneratorFactory()
self.gen = None
def __del__(self):
if self.db:
self.db.close()
self.db = None
def clearDock(self):
self.treeWidget.clear()
self.dbCombo.clear()
self.complexCombo.clear()
def isSpatialiteDatabase(self, dbName):
(dataSourceUri, credentials) = self.databases[dbName]
if dataSourceUri.host() == "":
return True
return False
def getUserCredentials(self, lyr):
dataSourceUri = QgsDataSourceURI( lyr.dataProvider().dataSourceUri() )
if dataSourceUri.host() == "":
return (None, None)
connInfo = dataSourceUri.connectionInfo()
(success, user, passwd ) = QgsCredentials.instance().get( connInfo, None, None )
# Put the credentials back (for yourself and the provider), as QGIS removes it when you "get" it
if success:
QgsCredentials.instance().put( connInfo, user, passwd )
return (user, passwd)
def updateComplexClass(self):
if self.db:
self.db.close()
self.db = None
if self.dbCombo.currentIndex() == 0:
return
dbName = self.dbCombo.currentText()
#getting the sql generator
self.gen = self.factory.createSqlGenerator(self.isSpatialiteDatabase(dbName))
(dataSourceUri, credentials) = self.databases[dbName]
#verifying the connection type
if self.isSpatialiteDatabase(dbName):
self.db = QSqlDatabase("QSQLITE")
self.db.setDatabaseName(dbName)
else:
self.db = QSqlDatabase("QPSQL")
self.db.setDatabaseName(dbName)
self.db.setHostName(dataSourceUri.host())
self.db.setPort(int(dataSourceUri.port()))
self.db.setUserName(credentials[0])
self.db.setPassword(credentials[1])
if not self.db.open():
print self.db.lastError().text()
self.populateComboBox()
def populateComboBox(self):
#getting all complex tables
self.complexCombo.clear()
self.complexCombo.addItem(self.tr("select a complex class"))
dbName = self.dbCombo.currentText()
(dataSourceUri, credentials) = self.databases[dbName]
#getting all complex tables
query = QSqlQuery(self.gen.getComplexTablesFromDatabase(), self.db)
while query.next():
self.complexCombo.addItem(query.value(0))
def getDataSources(self):
self.dbCombo.clear()
self.dbCombo.addItem(self.tr("select a database"))
#.........这里部分代码省略.........
示例14: CreateInomDialog
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import open [as 别名]
#.........这里部分代码省略.........
self.epsg = self.findEPSG()
print self.epsg
if self.epsg == -1:
self.bar.pushMessage("", self.tr("Coordinate Reference System not set or invalid!"), level=QgsMessageBar.WARNING)
else:
self.crs = QgsCoordinateReferenceSystem(self.epsg, QgsCoordinateReferenceSystem.EpsgCrsId)
if self.isSpatialite:
self.spatialiteCrsEdit.setText(self.crs.description())
self.spatialiteCrsEdit.setReadOnly(True)
else:
self.postGISCrsEdit.setText(self.crs.description())
self.postGISCrsEdit.setReadOnly(True)
except:
pass
def loadDatabase(self):
self.closeDatabase()
if self.isSpatialite:
fd = QtGui.QFileDialog()
self.filename = fd.getOpenFileName(filter='*.sqlite')
if self.filename:
self.spatialiteFileEdit.setText(self.filename)
self.db = QSqlDatabase("QSQLITE")
self.db.setDatabaseName(self.filename)
else:
self.db = QSqlDatabase("QPSQL")
(database, host, port, user, password) = self.getPostGISConnectionParameters(self.comboBoxPostgis.currentText())
self.db.setDatabaseName(database)
self.db.setHostName(host)
self.db.setPort(int(port))
self.db.setUserName(user)
self.db.setPassword(password)
try:
if not self.db.open():
print self.db.lastError().text()
else:
self.dbLoaded = True
self.setCRS()
except:
pass
def getPostGISConnectionParameters(self, name):
settings = QSettings()
settings.beginGroup('PostgreSQL/connections/'+name)
database = settings.value('database')
host = settings.value('host')
port = settings.value('port')
user = settings.value('username')
password = settings.value('password')
settings.endGroup()
return (database, host, port, user, password)
def getPostGISConnections(self):
settings = QSettings()
settings.beginGroup('PostgreSQL/connections')
currentConnections = settings.childGroups()
settings.endGroup()
return currentConnections
def populatePostGISConnectionsCombo(self):
self.comboBoxPostgis.clear()
self.comboBoxPostgis.addItem(self.tr("Select Database"))
self.comboBoxPostgis.addItems(self.getPostGISConnections())
def findEPSG(self):
sql = self.gen.getSrid()