Thursday, 31 May 2018

Loading Oracle Spatial Layers in standalone python qgis


I used below script to connect to postgres and load layers successfully.I want to aceive this using Oracle Spatial for both vector and raster loading.How can I achieve that?In other words what is the equivalent of postgis_utils for Oracle Spatial.From QGIS Desktop,I am able to load both raster and vector.This indicates QGIS has certain libraries to connect to Oracle and import GIS data.How can I use those libraries in standalone python script?


uri = QgsDataSourceURI()

uri.setConnection("localhost", "5432", "mydb", "postgres", "passcode")


db = postgis_utils.GeoDB(host="localhost", port=5432, dbname="v",user="postgres", passwd="passcode")
print db
tables =db.list_geotables()
print tables

render = QgsMapRenderer()


for t in tables :
uri.setDataSource(str(t[1]), str(t[0]), str(t[6]))
uri.uri()
vlayer = QgsVectorLayer(uri.uri(), str(t[0]), "postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
lst = [ vlayer.id() ]
render.setLayerSet(lst)
rect = QgsRectangle(render.fullExtent())
rect.scale(1.1)
render.setExtent(rect)


Answer



Figured it out by myself.I have used cx_Oracle library to accomplish this:


# Import system modules
from xml.dom.minidom import Document
import string
import os
import sys
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import *

from PyQt4.QtGui import QApplication
from PyQt4.QtXml import *
from ctypes import*
import cx_Oracle

strProjetName = "C:/OSGeo4W/apache/htdocs/QGIS-Web-Client-master/projects/myworld.qgs"

if os.path.isfile(strProjetName):
os.remove(strProjetName)


def add_LayersFromDB():
QGISAPP = QgsApplication(sys.argv, True)
QgsApplication.setPrefixPath(r"C:\OSGeo4W\apps\qgis", True)
QgsApplication.initQgis()

#Connect to Oracle and Fetch Table Names
con = cx_Oracle.connect('testinstance/testinstance@189.60.67.146:1521/new')
print con.version
cur = con.cursor()
cur.execute(u"select TABLE_NAME from user_tab_columns where data_type='SDO_GEOMETRY'")


tables = cur.fetchall()

QgsProject.instance().setFileName(strProjetName)
print QgsProject.instance().fileName()
render = QgsMapRenderer()

uri = QgsDataSourceURI()
uri.setConnection("189.60.67.146", "1521", "new", "testinstance", "testinstance")


render = QgsMapRenderer()

for t in tables :
print str(t[0])

uri.setDataSource('', str(t[0]), "GEOMETRY")
uri.uri()
vlayer = QgsVectorLayer(uri.uri(),str(t[0]), 'oracle')
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
lst = [ vlayer.id() ]

render.setLayerSet(lst)
rect = QgsRectangle(render.fullExtent())
rect.scale(1.1)
render.setExtent(rect)

QgsProject.instance().write()

cur.close()
con.close()


QgsApplication.exitQgis()


add_LayersFromDB()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...