Nous utilisons des cookies pour vous garantir la meilleure expérience sur notre site. Si vous continuez à utiliser ce dernier, nous considèrerons que vous acceptez l'utilisation des cookies. J'ai compris ! ou En savoir plus !.
banniere

Le portail francophone de la géomatique


Toujours pas inscrit ? Mot de passe oublié ?
Nom d'utilisateur    Mot de passe              Toujours pas inscrit ?   Mot de passe oublié ?

Annonce

Printemps des cartes 2024

#1 Tue 28 May 2013 10:56

anasstopog
Participant occasionnel
Date d'inscription: 7 Mar 2013
Messages: 10

connexion à postgres et ajout d'une colonne à la table d'attribut

Bonjour tt le monde , je voulais savoir comment ajouter une colonne à la table d'attribut qui aura comme valeur un calcul à partir de postgres.
j'ai essayé avec ce code, mais je sais bien qu'il ya des erreurs la dessus , est ce qu'il y'a quelqu'un qui peut m'aider !! :


   
from PyQt4.QtCore import *
import psycopg2

#------------------------------------------------------------------------------#
#                                  PARAMETERS                                  #
#------------------------------------------------------------------------------#

# Name of the column to be created
# /!\ must not exceed 10 characters
NEW_COL = 'distance_route'

# Type of the new column (probably QVariant.Double or QVariant.Int)
COL_TYPE = QVariant.Double

# Function to calculate the new value
def myFunction(cur.execute) :
    '''
    Calculate the new field for the selected element
     
    :param attrs: attributeMap with numeric keys replaced by column names
    :returns:     value of the new field
    '''
    #i_sante = attrs['i_sante'].toFloat()
    #i_ecole = attrs['i_ecole'].toFloat()
    #i_college = attrs['i_college'].toFloat()
    #i_piste = attrs['i_piste'].toFloat()
    #i_route = attrs['i_route'].toFloat()
    #return (1.75 * i_route + 2 * i_piste + 1.5 * i_ecole +  i_college + 1.75 * i_sante)
    return(cur.execute)
#------------------------------------------------------------------------------#
#                                    SCRIPT                                                                #
#------------------------------------------------------------------------------#

# Select layer
layer = qgis.utils.iface.activeLayer()
provider = layer.dataProvider()

# Create the new column
res = provider.addAttributes( [ QgsField(NEW_COL, COL_TYPE) ] )

# Select and map attributes
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
attrNames = [ str(provider.fields()[i].name()) for i in allAttrs ]
attrDict = dict(zip(attrNames, allAttrs))

# Connexion à Postgis
conn = psycopg2.connect("dbname='test2' user='postgres' host='localhost' password='postgres'")
cur = conn.cursor()
cur.execute("""Update douar as t1
SET distance_route= (SELECT ST_Distance(t1.the_geom, t2.the_geom) FROM routes as t2
ORDER BY ST_Distance(t1.the_geom, t2.the_geom) LIMIT 1);""")

# Iterate over the features
feat = QgsFeature()
feat_2_chg = {}
while provider.nextFeature(feat):
    attrs = feat.attributeMap()
    attrs = dict([ (i, attrs[attrDict[i]]) for i in attrDict ])
    ind = myFunction(cur.execute)
    if not ind == None :
        feat_2_chg[feat.id()] = {attrDict[NEW_COL] : QVariant(ind)}

# Update the layer
provider.changeAttributeValues(feat_2_chg)

Hors ligne

 

Pied de page des forums

Powered by FluxBB