Guest User

Untitled

a guest
Dec 7th, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.88 KB | None | 0 0
  1. from osgeo import ogr
  2.  
  3. filepath = 'C:/Users/username/Desktop/path/clip.shp' # set the filepath
  4. layer_name = filepath[:-4].split('/')[-1] # get the layer name
  5. driver = ogr.GetDriverByName ("ESRI Shapefile")
  6. ogr_ds = driver.Open(filepath)
  7. TEST=2
  8. sql = "SELECT myfield FROM %s WHERE OBJECTID=%s" %(layer_name,TEST)
  9. layer = ogr_ds.ExecuteSQL(sql)
  10. feat = layer.GetNextFeature()
  11. val = feat.GetField(0)
  12.  
  13. print (val.decode('utf-8'))
  14.  
  15. import psycopg2
  16.  
  17. try:
  18. conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'")
  19. except:
  20. print "I am unable to connect to the database"
  21.  
  22. c = conn.cursor()
  23. c.execute('SELECT * FROM mytesttable')
  24. c.fetchall()
  25.  
  26. c.execute('COMMIT;')
  27.  
  28. def get_dbparams(self):
  29. # Get db connections params #
  30. DB = 'somedb'
  31. PORT = 5432
  32. HOST = '11.22.333.44'
  33.  
  34. user = self.get_userrole()
  35.  
  36. if user == GrukosUser.READER:
  37. db_params = {
  38. 'dbname': DB,
  39. 'user': 'grukosreader',
  40. 'host': HOST,
  41. 'password': base64.b64decode('SDFADSASDFADF'),
  42. 'port': PORT
  43. }
  44. return db_params
  45. elif user == GrukosUser.WRITER:
  46. db_params = {
  47. 'dbname': DB,
  48. 'user': 'grukoswriter',
  49. 'host': HOST,
  50. 'password': base64.b64decode('SDFGSGSDFGSDFGSDF'),
  51. 'port': PORT
  52. }
  53. return db_params
  54. else:
  55. return None
  56.  
  57. db = MyDb()
  58. params = db.get_dbparams()
  59.  
  60. uri = QgsDataSourceURI()
  61. uri.setConnection(params['host'], str(params['port']), params['dbname'], params['user'], params['password'])
  62.  
  63. uri.setDataSource("myschema", "mytablename", None, "mycolumn={}".format(myvalue))
  64.  
  65. uri.setDataSource("myschema", "mytablename", "mygeom", "mycolumn={}".format(myvalue))
  66.  
  67. uri.setDataSource("myschema", "mytablename", None)
  68.  
  69. uri.setDataSource("myschema", "mytablename", "geom")
  70.  
  71. uri.setDataSource("myschema", "mytablename", "geom", aKeyColumn='id')
  72. uri.setKeyColumn('id')
  73.  
  74. vlayer = QgsVectorLayer(uri.uri(), "mylayername", "postgres")
  75.  
  76. if not vlayer.isValid():
  77. ...
  78.  
  79. QgsMapLayerRegistry.instance().addMapLayer(vlayer, True)
  80.  
  81. def get_projectid(self, gkoid):
  82. """ Use a PostgreSQL function to translate gkoid to projectid """
  83. sql = 'SELECT myschema.mypgfunction({});'.format(gkoid)
  84. cur = self.execute_sql(sql)
  85. rows_tuple = cur.fetchone()
  86. projectid = rows_tuple[0]
  87.  
  88. return projekcid, sql
  89.  
  90. def execute_sql(self, sql, dict_cursor=True, print_sql=False):
  91.  
  92. """ Execute a SQL query
  93. :param sql: SQL to be executed
  94. :param dict_cursor: Flag indicating if cursor is a dict or not. Use false for scalar queries
  95. :param print_sql: Flag indicating if sql is to be printet
  96. :return: returns a cursor
  97. """
  98.  
  99. if print_sql: print sql
  100. conn = psycopg2.connect(**self.get_dbparams())
  101.  
  102. if dict_cursor:
  103. cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
  104. else:
  105. cur = conn.cursor()
  106.  
  107. try:
  108. cur.execute(sql)
  109. return cur
  110. except psycopg2.DatabaseError, e:
  111. print 'Some error {}'.format(e)
  112. sys.exit(1)
  113. finally:
  114. pass
  115. #TODO
  116. #if conn:
  117. # conn.close()
  118.  
  119. def enable_qgis_log(filename = 'D:gqis.log', haltApp = False, haltMsg = 'stop'):
  120. """ Very useful when QGIS crashes on PGSQL error
  121. :param filename: Filename and path for log file
  122. :param haltApp: Halts the application with a modal dialog
  123. :param haltMsg: Message to user when showing model stopping dialog
  124. :rtype: None
  125. """
  126. def write_log_message(message, tag, level):
  127. with open(filename, 'a') as logfile:
  128. logfile.write('{tag}({level}): {message}'.format(tag=tag, level=level, message=message))
  129.  
  130. QgsMessageLog.instance().messageReceived.connect(write_log_message)
  131.  
  132. if haltApp:
  133. QtGui.QMessageBox.information(None, GrukosAux.GRUKOS, "{}".format(haltMsg.encode('cp1252')), QtGui.QMessageBox.Ok)
Add Comment
Please, Sign In to add comment