Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from osgeo import ogr
- filepath = 'C:/Users/username/Desktop/path/clip.shp' # set the filepath
- layer_name = filepath[:-4].split('/')[-1] # get the layer name
- driver = ogr.GetDriverByName ("ESRI Shapefile")
- ogr_ds = driver.Open(filepath)
- TEST=2
- sql = "SELECT myfield FROM %s WHERE OBJECTID=%s" %(layer_name,TEST)
- layer = ogr_ds.ExecuteSQL(sql)
- feat = layer.GetNextFeature()
- val = feat.GetField(0)
- print (val.decode('utf-8'))
- import psycopg2
- try:
- conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'")
- except:
- print "I am unable to connect to the database"
- c = conn.cursor()
- c.execute('SELECT * FROM mytesttable')
- c.fetchall()
- c.execute('COMMIT;')
- def get_dbparams(self):
- # Get db connections params #
- DB = 'somedb'
- PORT = 5432
- HOST = '11.22.333.44'
- user = self.get_userrole()
- if user == GrukosUser.READER:
- db_params = {
- 'dbname': DB,
- 'user': 'grukosreader',
- 'host': HOST,
- 'password': base64.b64decode('SDFADSASDFADF'),
- 'port': PORT
- }
- return db_params
- elif user == GrukosUser.WRITER:
- db_params = {
- 'dbname': DB,
- 'user': 'grukoswriter',
- 'host': HOST,
- 'password': base64.b64decode('SDFGSGSDFGSDFGSDF'),
- 'port': PORT
- }
- return db_params
- else:
- return None
- db = MyDb()
- params = db.get_dbparams()
- uri = QgsDataSourceURI()
- uri.setConnection(params['host'], str(params['port']), params['dbname'], params['user'], params['password'])
- uri.setDataSource("myschema", "mytablename", None, "mycolumn={}".format(myvalue))
- uri.setDataSource("myschema", "mytablename", "mygeom", "mycolumn={}".format(myvalue))
- uri.setDataSource("myschema", "mytablename", None)
- uri.setDataSource("myschema", "mytablename", "geom")
- uri.setDataSource("myschema", "mytablename", "geom", aKeyColumn='id')
- uri.setKeyColumn('id')
- vlayer = QgsVectorLayer(uri.uri(), "mylayername", "postgres")
- if not vlayer.isValid():
- ...
- QgsMapLayerRegistry.instance().addMapLayer(vlayer, True)
- def get_projectid(self, gkoid):
- """ Use a PostgreSQL function to translate gkoid to projectid """
- sql = 'SELECT myschema.mypgfunction({});'.format(gkoid)
- cur = self.execute_sql(sql)
- rows_tuple = cur.fetchone()
- projectid = rows_tuple[0]
- return projekcid, sql
- def execute_sql(self, sql, dict_cursor=True, print_sql=False):
- """ Execute a SQL query
- :param sql: SQL to be executed
- :param dict_cursor: Flag indicating if cursor is a dict or not. Use false for scalar queries
- :param print_sql: Flag indicating if sql is to be printet
- :return: returns a cursor
- """
- if print_sql: print sql
- conn = psycopg2.connect(**self.get_dbparams())
- if dict_cursor:
- cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
- else:
- cur = conn.cursor()
- try:
- cur.execute(sql)
- return cur
- except psycopg2.DatabaseError, e:
- print 'Some error {}'.format(e)
- sys.exit(1)
- finally:
- pass
- #TODO
- #if conn:
- # conn.close()
- def enable_qgis_log(filename = 'D:gqis.log', haltApp = False, haltMsg = 'stop'):
- """ Very useful when QGIS crashes on PGSQL error
- :param filename: Filename and path for log file
- :param haltApp: Halts the application with a modal dialog
- :param haltMsg: Message to user when showing model stopping dialog
- :rtype: None
- """
- def write_log_message(message, tag, level):
- with open(filename, 'a') as logfile:
- logfile.write('{tag}({level}): {message}'.format(tag=tag, level=level, message=message))
- QgsMessageLog.instance().messageReceived.connect(write_log_message)
- if haltApp:
- QtGui.QMessageBox.information(None, GrukosAux.GRUKOS, "{}".format(haltMsg.encode('cp1252')), QtGui.QMessageBox.Ok)
Add Comment
Please, Sign In to add comment