本文整理汇总了Python中PyQt4.QtSql.QSqlDatabase.setDatabaseName方法的典型用法代码示例。如果您正苦于以下问题:Python QSqlDatabase.setDatabaseName方法的具体用法?Python QSqlDatabase.setDatabaseName怎么用?Python QSqlDatabase.setDatabaseName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtSql.QSqlDatabase
的用法示例。
在下文中一共展示了QSqlDatabase.setDatabaseName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: makeValueRelationDict
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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
示例2: initDb
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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
示例3: getEDGVDbsFromServer
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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
示例4: getSpatialiteDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [as 别名]
def getSpatialiteDatabase(self):
db = None
fd = QFileDialog()
filename = fd.getOpenFileName(filter='*.sqlite')
if filename:
db = QSqlDatabase("QSQLITE")
db.setDatabaseName(filename)
return (filename, db)
示例5: getPostGISDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [as 别名]
def getPostGISDatabase(self, postGISConnection):
db = None
db = QSqlDatabase("QPSQL")
(database, host, port, user, password) = self.getPostGISConnectionParameters(postGISConnection)
db.setDatabaseName(database)
db.setHostName(host)
db.setPort(int(port))
db.setUserName(user)
db.setPassword(password)
return db
示例6: getDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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 setDatabaseName [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: getDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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
示例9: makeValueRelationDict
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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
示例10: dropDatabase
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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)
示例11: getConnection
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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
示例12: SpatialiteDb
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [as 别名]
class SpatialiteDb(AbstractDb):
def __init__(self):
'''
Constructor
'''
super(SpatialiteDb,self).__init__()
self.db = QSqlDatabase('QSQLITE')
self.gen = SqlGeneratorFactory().createSqlGenerator(True)
def getDatabaseName(self):
'''
Gets the database name
'''
return self.db.databaseName().split('.sqlite')[0].split('/')[-1]
def connectDatabase(self, conn = None):
'''
Connects to database
conn: Database name
'''
if conn is None:
self.connectDatabaseWithGui()
else:
self.db.setDatabaseName(conn)
def connectDatabaseWithGui(self):
'''
Connects to database using user interface dialog
'''
fd = QFileDialog()
filename = fd.getOpenFileName(caption=self.tr('Select a DSGTools Spatialite file'),filter=self.tr('Spatialite file databases (*.sqlite)'))
self.db.setDatabaseName(filename)
def listGeomClassesFromDatabase(self, primitiveFilter = []):
'''
Gets a list with geometry classes from database
'''
self.checkAndOpenDb()
classList = []
sql = self.gen.getTablesFromDatabase()
query = QSqlQuery(sql, self.db)
if not query.isActive():
self.db.close()
raise Exception(self.tr("Problem listing geom classes: ")+query.lastError().text())
while query.next():
tableName = str(query.value(0))
layerName = tableName
if tableName.split("_")[-1] == "p" or tableName.split("_")[-1] == "l" \
or tableName.split("_")[-1] == "a":
classList.append(layerName)
return classList
def listComplexClassesFromDatabase(self):
'''
Gets a list with complex classes from database
'''
self.checkAndOpenDb()
classList = []
sql = self.gen.getTablesFromDatabase()
query = QSqlQuery(sql, self.db)
if not query.isActive():
self.db.close()
raise Exception(self.tr("Problem listing complex classes: ")+query.lastError().text())
while query.next():
tableName = str(query.value(0))
layerName = tableName
tableSchema = layerName.split('_')[0]
if tableSchema == 'complexos':
classList.append(layerName)
return classList
def getStructureDict(self):
'''
Gets database structure according to the edgv version
'''
self.checkAndOpenDb()
classDict = dict()
sql = self.gen.getStructure(self.getDatabaseVersion())
query = QSqlQuery(sql, self.db)
if not query.isActive():
self.db.close()
raise Exception(self.tr("Problem getting database structure: ")+query.lastError().text())
while query.next():
className = str(query.value(0))
classSql = str(query.value(1))
if className.split('_')[0] == 'complexos' or className.split('_')[-1] in ['p','l','a']:
if className not in classDict.keys():
classDict[className]=dict()
classSql = classSql.split(className)[1]
sqlList = classSql.replace('(','').replace(')','').replace('\"','').replace('\'','').split(',')
for s in sqlList:
fieldName = str(s.strip().split(' ')[0])
classDict[className][fieldName]=fieldName
if 'GEOMETRY' in classDict[className].keys():
classDict[className]['GEOMETRY'] = 'geom'
if 'geometry' in classDict[className].keys():
classDict[className]['geometry'] = 'geom'
if 'OGC_FID' in classDict[className].keys():
#.........这里部分代码省略.........
示例13: PostgisDb
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [as 别名]
class PostgisDb(AbstractDb):
def __init__(self):
super(PostgisDb,self).__init__()
self.db = QSqlDatabase('QPSQL')
self.gen = SqlGeneratorFactory().createSqlGenerator(False)
def getDatabaseName(self):
return self.db.databaseName()
def connectDatabase(self,conn=None):
if conn.split(':')[0] == 'PG':
connSplit = conn.split(' ')
parDict = dict()
for i in connSplit[1::]:
par = i.split('=')
parDict[par[0]]=par[1]
self.connectDatabaseWithParameters(parDict['host'], parDict['port'], parDict['dbname'], parDict['user'], parDict['password'])
else:
self.connectDatabaseWithQSettings(conn)
def connectDatabaseWithGui(self):
return None
def connectDatabaseWithParameters(self, host, port, database, user, password):
self.db.setHostName(host)
if type(port) != 'int':
self.db.setPort(int(port))
else:
self.db.setPort(port)
self.db.setDatabaseName(database)
self.db.setUserName(user)
if not password or password == '':
conInfo = 'host='+host+' port='+port+' dbname='+database
check = False
while not check:
try:
(success, user, password) = QgsCredentials.instance().get(conInfo, user, None)
if not success:
return
self.db.setPassword(password)
check = True
self.checkAndOpenDb()
QgsCredentials.instance().put(conInfo, user, password)
except:
pass
else:
self.db.setPassword(password)
def connectDatabaseWithQSettings(self, name):
(host, port, database, user, password) = self.getConnectionFromQSettings(name)
self.db.setHostName(host)
if type(port) != 'int':
self.db.setPort(int(port))
else:
self.db.setPort(port)
self.db.setDatabaseName(database)
self.db.setUserName(user)
if not password or password == '':
conInfo = 'host='+host+' port='+port+' dbname='+database
check = False
while not check:
try:
(success, user, password) = QgsCredentials.instance().get(conInfo, user, None)
if not success:
return
self.db.setPassword(password)
check = True
self.checkAndOpenDb()
QgsCredentials.instance().put(conInfo, user, password)
except:
pass
else:
self.db.setPassword(password)
def getDatabaseVersion(self):
try:
self.checkAndOpenDb()
except:
return '-1'
sqlVersion = self.gen.getEDGVVersion()
queryVersion = QSqlQuery(sqlVersion, self.db)
while queryVersion.next():
version = queryVersion.value(0)
return version
def listGeomClassesFromDatabase(self):
try:
self.checkAndOpenDb()
except:
return []
classList = []
sql = self.gen.getTablesFromDatabase()
query = QSqlQuery(sql, self.db)
while query.next():
tableSchema = query.value(0)
tableName = query.value(1)
layerName = tableSchema+'.'+tableName
if tableName.split("_")[-1] == "p" or tableName.split("_")[-1] == "l" \
or tableName.split("_")[-1] == "a":
#.........这里部分代码省略.........
示例14: ComplexWindow
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [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"))
#.........这里部分代码省略.........
示例15: SpatialiteDb
# 需要导入模块: from PyQt4.QtSql import QSqlDatabase [as 别名]
# 或者: from PyQt4.QtSql.QSqlDatabase import setDatabaseName [as 别名]
class SpatialiteDb(AbstractDb):
def __init__(self):
super(SpatialiteDb,self).__init__()
self.db = QSqlDatabase('QSQLITE')
self.gen = SqlGeneratorFactory().createSqlGenerator(True)
def getDatabaseName(self):
return self.db.databaseName().split('.sqlite')[0].split('/')[-1]
def connectDatabase(self, conn = None):
if conn is None:
self.connectDatabaseWithGui()
else:
self.db.setDatabaseName(conn)
def connectDatabaseWithGui(self):
fd = QFileDialog()
filename = fd.getOpenFileName(caption=self.tr('Select a DSGTools Spatialite file'),filter=self.tr('Spatialite file databases (*.sqlite)'))
self.db.setDatabaseName(filename)
def connectDatabaseWithQSettings(self, name):
return None
def connectDatabaseWithParameters(self, host, port, database, user, password):
return None
def listGeomClassesFromDatabase(self):
try:
self.checkAndOpenDb()
except:
return []
classList = []
sql = self.gen.getTablesFromDatabase()
query = QSqlQuery(sql, self.db)
while query.next():
tableName = str(query.value(0))
layerName = tableName
if tableName.split("_")[-1] == "p" or tableName.split("_")[-1] == "l" \
or tableName.split("_")[-1] == "a":
classList.append(layerName)
return classList
def listComplexClassesFromDatabase(self):
try:
self.checkAndOpenDb()
except:
return []
classList = []
sql = self.gen.getTablesFromDatabase()
query = QSqlQuery(sql, self.db)
while query.next():
tableName = str(query.value(0))
layerName = tableName
tableSchema = layerName.split('_')[0]
if tableSchema == 'complexos':
classList.append(layerName)
return classList
def getConnectionFromQSettings(self, conName):
return None
def storeConnection(self, server):
return None
def getServerConfiguration(self, name):
return None
def getStructureDict(self):
try:
self.checkAndOpenDb()
except:
return dict()
classDict = dict()
sql = self.gen.getStructure(self.getDatabaseVersion())
query = QSqlQuery(sql, self.db)
while query.next():
className = str(query.value(0))
classSql = str(query.value(1))
if className.split('_')[0] == 'complexos' or className.split('_')[-1] in ['p','l','a']:
if className not in classDict.keys():
classDict[className]=dict()
classSql = classSql.split(className)[1]
sqlList = classSql.replace('(','').replace(')','').replace('\"','').replace('\'','').split(',')
for s in sqlList:
fieldName = str(s.strip().split(' ')[0])
classDict[className][fieldName]=fieldName
if 'GEOMETRY' in classDict[className].keys():
classDict[className]['GEOMETRY'] = 'geom'
if 'OGC_FID' in classDict[className].keys():
classDict[className]['OGC_FID'] = 'id'
return classDict
def makeOgrConn(self):
constring = self.db.databaseName()
return constring
def getNotNullDict(self):
#.........这里部分代码省略.........