QGIS uses the OGR library to read and write vector data formats, including ESRI shapefiles, MapInfo and MicroStation file formats, AutoCAD DXF, PostGIS, SpatiaLite, Oracle Spatial and MSSQL Spatial databases, and many more. GRASS vector and PostgreSQL support is supplied by native QGIS data provider plugins. Vector data can also be loaded in read mode from zip and gzip archives into QGIS. As of the date of this document, 69 vector formats are supported by the OGR library (see OGR-SOFTWARE-SUITE in Referências Bibliográficas e Web). The complete list is available at http://www.gdal.org/ogr/ogr_formats.html.
Nota
Not all of the listed formats may work in QGIS for various reasons. For example, some require external commercial libraries, or the GDAL/OGR installation of your OS may not have been built to support the format you want to use. Only those formats that have been well tested will appear in the list of file types when loading a vector into QGIS. Other untested formats can be loaded by selecting *.*.
Procedimentos com dados vetoriais GRASS são descritos na Seção Integração com SIG GRASS.
This section describes how to work with several common formats: ESRI shapefiles, PostGIS layers, SpatiaLite layers, OpenStreetMap vectors, and Comma Separated data (CSV). Many of the features available in QGIS work the same, regardless of the vector data source. This is by design, and it includes the identify, select, labelling and attributes functions.
Nota
QGIS supports (multi)point, (multi)line, (multi)polygon, CircularString, CompoundCurve, CurvePolygon, MultiCurve, MultiSurface feature types, all with Z and/or M values.
You should note also that some driver doesn’t support some of these feature types like CircularString, CompoundCurve, CurvePolygon, MultiCurve, MultiSurface feature type. QGIS will convert them to (multi)polygon feature.
To load a layer from a file (like a Shapefile, a Mapinfo or a dxf
layer), click on the
Add Vector Layer toolbar button; or
type Ctrl+Shift+V. This will bring up a new window (see
figure_vector_1).
Figure Vector 1:
Add Vector Layer Dialog
From the available options check File. Click on
[Browse]. That will bring up a standard open file dialog
(see figure_vector_2), which allows you to navigate the file system and load a
shapefile or other supported data source. The selection box Filter
allows you to preselect some OGR-supported file formats.
You can also select the encoding for the file if desired.
Figure Vector 2:
Open an OGR Supported Vector Layer Dialog
Selecting a file from the list and clicking [Open] loads it into QGIS. Figure_vector_3 shows QGIS after loading the alaska.shp file.
Figure Vector 3:
QGIS with Shapefile of Alaska loaded
Dica
Cores das camadas
Quando você adiciona uma camada ao mapa, é atribuída uma cor aleatória. Na adição de mais de uma camada de uma vez, são atribuídas cores diferentes para cada camada.
Once a file is loaded, you can zoom around it using the map navigation tools. To change the style of a layer, open the Layer Properties dialog by double clicking on the layer name or by right-clicking on the name in the legend and choosing Properties from the context menu. See section Menu Estilo for more information on setting symbology of vector layers.
Dica
Carregando camadas e armazenando projetos em unidades externas no OS X
No OS X, unidades portáteis que são armazenadas além do disco rígido principal não aparecem no File ‣Open Project `como esperado. Para resolver isso estamos trabalhando em uma forma mais nativa do OS X com caixa de diálogo abrir/salvar. Como alternativa, você pode digitar ‘/Volumes’ no campo Nome do arquivo e pressione :kbd:`Voltar. Depois, você pode navegar para unidades externas ou armazenadas em rede.
Nota
DXF files containing several geometry types (point, line and/or polygon), the name of the layer will be made from <filename.dxf> entities <geometry type>.
Nota
You can also drag and drop the file(s) into the Layers Panel from either the files browser or the QGIS Browser panel. If the layer contains several geometry types, a new windows will ask you to select the sublayer. This often occurs with GPX, Mapinfo or DXF files format.
To load some specific format like ArcInfo Binary Coverage, UK.
National Transfer Format, as well as the raw TIGER format of the US Census
Bureau or OpenfileGDB, click on the
Add Vector Layer
toolbar button or press Ctrl+Shift+V to open the
Add Vector Layer dialog. Select
Directory as Source type. Change the file type filter
Files of type
to the format you want to open, for
example ‘Arc/Info Binary Coverage’. Navigate to the directory that contains the
coverage file or the file, and select it.
The ESRI shapefile is still one of the most used vector file format in QGIS. However, this file format has some limitation that some other file format have not (like Geopackage, spatialite). Support is provided by the OGR Simple Feature Library (http://www.gdal.org/ogr/).
Um shapefile consiste na verdade de um conjunto de vários arquivos. Os três seguintes são necessários:
.shp arquivo que contém as formas vetoriais.
.dbf arquivo que contém os atributos no formato dBase..
.shx arquivos index.
Shapefiles também podem incluir um arquivo com a extensão .prj que contém as informações de projeção. Embora seja muito útil um arquivo de projeção, não é obrigatória. Um conjunto de dados shapefile pode conter arquivos adicionais. Para mais detalhes veja a especificação técnica ESRI em: http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf.
Improving Performance for Shapefiles
To improve the performance of drawing a shapefile, you can create a spatial index. A spatial index will improve the speed of both zooming and panning. Spatial indexes used by QGIS have a .qix extension.
Siga estes passos para criar o índice:
Abra a caixa de diálogo Propriedades da camada clicando duas vezes sobre o nome do shapefile na legenda ou com o botão direito do mouse e escolha Propriedades a partir do menu de contexto.
Na guia :guilabel:’Geral’, clique no botão [Criar índice espacial].
Problem loading a shape .prj file
If you load a shapefile with a .prj file and QGIS is not able to read the coordinate reference system from that file, you will need to define the proper projection manually within the General tab of the Layer Properties dialog of the layer by clicking the [Specify...] button. This is due to the fact that .prj files often do not provide the complete projection parameters as used in QGIS and listed in the CRS dialog.
For the same reason, if you create a new shapefile with QGIS, two different projection files are created: a .prj file with limited projection parameters, compatible with ESRI software, and a .qpj file, providing the complete parameters of the used CRS. Whenever QGIS finds a .qpj file, it will be used instead of the .prj.
Dados em tabelas é um formato muito comum e amplamente utilizado devido à sua simplicidade e facilidade de acesso - os dados podem ser visualizados e editados até mesmo em um editor de texto simples. Um arquivo de texto delimitado é uma tabela de atributos com cada coluna separados por um caracter definido e cada linha separada por uma quebra de linha. A primeira linha geralmente contém os nomes das colunas. Um tipo comum de arquivo de texto delimitado é um arquivo CSV (Comma Separated Values), com cada coluna separado por uma vírgula.
Esses arquivos de dados também podem conter informações sobre a posição em duas formas principais:
Coordenadas de ponto separadas por colunas
Texto bem conhecido (WKT) representado por geometria
QGIS allows you to load a delimited text file as a layer or ordinal table. But first check that the file meets the following requirements:
O arquivo deve ter uma linha de cabeçalho delimitada de nomes de campo. Esta deve ser a primeira linha do arquivo de texto.
A linha de cabeçalho deve conter campo (s) com a definição da geometria. Estes campo (s) pode ter qualquer nome.
As coordenadas X e Y (se a geometria for definida pelas coordenadas) deverá ser especificada como números. O sistema de coordenadas não é importante.
As an example of a valid text file, we import the elevation point data file elevp.csv that comes with the QGIS sample dataset (see section Amostra de Dados):
X;Y;ELEV
-300120;7689960;13
-654360;7562040;52
1640;7512840;3
[...]
Alguns itens a serem observados sobre o arquivo de texto:
O arquivo de texto exemplo usa ; (ponto e vírgula) como delimitador. Qualquer caractére pode ser usado para delimitar os campos.
A primeira linha é a linha de cabeçalho. Ela contém os campos X, Y e ELEV.
Sem aspas (") são usados para delimitar os campos de texto.
A coordenada X está contida no campo X.
A coordenada Y está contida no campo Y.
Features with curved geometries (CircularString, CurvePolygon and CompoundCurve) are supported. Here are three examples of such geometry types as a delimited text with WKT geometries:
Label;WKT_geom
CircularString;CIRCULARSTRING(268 415,227 505,227 406)
CurvePolygon;CURVEPOLYGON(CIRCULARSTRING(1 3, 3 5, 4 7, 7 3, 1 3))
CompoundCurve;COMPOUNDCURVE((5 3, 5 13), CIRCULARSTRING(5 13, 7 15,
9 13), (9 13, 9 3), CIRCULARSTRING(9 3, 7 1, 5 3))
Delimited Text supports also Z and M coordinates in geometries:
LINESTRINGM(10.0 20.0 30.0, 11.0 21.0 31.0)
Click the toolbar icon Add Delimited Text Layer in the
Manage layers toolbar to open the Create a Layer from a
Delimited Text File dialog, as shown in figure_delimited_text_1.
Figure Delimited Text 1:
Delimited Text Dialog
First, select the file to import (e.g., qgis_sample_data/csv/elevp.csv)
by clicking on the [Browse] button. Once the file is selected, QGIS
attempts to parse the file with the most recently used delimiter. To enable QGIS to properly parse the
file, it is important to select the correct delimiter. You can specify a
delimiter by activating Custom delimiters, or by activating
Regular expression delimiter and entering
text into the Expression field. For example, to
change the delimiter to tab, use \t (this is a regular expression for the
tab character).
Once the file is parsed, set Geometry definition to
Point coordinates and choose the X and Y
fields from the dropdown lists. If the coordinates are defined as
degrees/minutes/seconds, activate the
DMS coordinates
checkbox.
Finally, enter a layer name (e.g., elevp), as shown in figure_delimited_text_1. To add the layer to the map, click [OK]. The delimited text file now behaves as any other map layer in QGIS.
Há também uma opção de ajuda que permite cortar espaços iniciais e finais dos campos no guilabel: ‘campos da guarnição’. Além disso, é possível no guilabel: descartar campos vazios. Se necessário, você pode forçar uma vírgula para ser o separador decimal ativando no guilabel: ‘separador decimal por vírgula’.
If spatial information is represented by WKT, activate the
Well Known Text option and select the field with the WKT definition for
point, line or polygon objects. If the file contains non-spatial data, activate
No geometry (attribute only table) and it will be
loaded as an ordinal table.
Additionally, you can enable:
In recent years, the OpenStreetMap project has gained popularity because in many countries no free geodata such as digital road maps are available. The objective of the OSM project is to create a free editable map of the world from GPS data, aerial photography or local knowledge. To support this objective, QGIS provides support for OSM data.
QGIS integrates OpenStreetMap import as a core functionality.
Para conectar-se aos dados do servidor OSM e de download, abra o menu: ‘Vetor -> OpenStreetMap -> Carregar dados’. Você pode pular esta etapa se você já obteve um arquivo XML usando .osm, JOSM, API ou qualquer outra fonte.
No menu ‘Vetor -> OpenStreetMap -> Importar topologia de um arquivo XML’ irá converter o seu: arquivo .osm em um banco de dados SpatiaLite e criar uma conexão de banco de dados correspondente.
PostGIS layers are stored in a PostgreSQL database. The advantages of PostGIS are the spatial indexing, filtering and query capabilities it provides. Using PostGIS, vector functions such as select and identify work more accurately than they do with OGR layers in QGIS.
The first time you use a PostGIS data source, you must
create a connection to the PostgreSQL database that contains the data. Begin by
clicking on the
Add PostGIS Layer toolbar
button, selecting the
Add PostGIS Layer...
option from the Layer menu, or typing Ctrl+Shift+D. You
can also open the Add Vector Layer dialog and select
Database. The Add PostGIS Table(s)
dialog will be displayed. To access the connection manager, click on the
[New] button to display the Create a New PostGIS Connection
dialog. The parameters required for a connection are:
Nome: Um nome para esta conexão. Pode ser o mesmo que o da Base de dados.
Porta: Número da porta do servidor de banco de dados PostgreSQL atende. A porta padrão é 5432.
Banco de dados: Nome do banco de dados.
Desabilitar: tenta apenas conexão SSL não criptografada.
Permitir: tenta uma conexão não-SSL. Se isso não funcionar, tenta uma conexão SSL.
Preferir: tenta uma conexão SSL. Se isso não funcionar, tenta uma conexão não-SSL.
Requer: tenta apenas conexão SSL.
Usuário: Nome do usuário usado para logar na base de dados.
Senha: Senha usada com Nome do Usuário para conectar ao banco de dados.
Opcionalmente, você pode ativar as seguintes caixas de seleção:
: guilabel: Não resolve tipo de colunas sem restrições (geometria)
:guilabel:`Apenas olhar no esquema ‘público’
Uma vez que todos os parâmetros e as opções estão configuradas, você pode testar a conexão clicando no botão [Testar Conexão].
Dica
Use estimated table metadata to speed up operations
When initializing layers, various queries may be needed to establish the characteristics of the geometries stored in the database table. When the Use estimated table metadata option is checked, these queries examine only a sample of the rows and use the table statistics, rather than the entire table. This can drastically speed up operations on large datasets, but may result in incorrect characterization of layers (eg. the feature count of filtered layers will not be accurately determined) and may even cause strange behaviour in case columns that are supposed to be unique actually are not.
Once you have one or more connections defined, you can
load layers from the PostgreSQL database. Of course, this requires having data in
PostgreSQL. See section Importação de dados no PostgreSQL for a discussion on
importing data into the database.
Para colocar uma camada no PostGIS, execute os seguintes passos:
Escolha a conexão a partir da lista solta a baixo e clique em [Conectar].
Opcionalmente, use Opções de busca para definir quais recursos serão carregados a partir da camada ou use o botão de [Definir Filtro] para iniciar Ferramenta de Consulta.
Encontre a camada(s) que deseja adicionar na lista de camadas disponíveis.
Selecione-a clicando sobre ela. Você pode selecionar várias camadas pressionando a tecla Shift enquanto clica. Consulte a Seção Query Builder para obter informações sobre como usar o Query Builder PostgreSQL para melhor definição da camada.
Clique no botão [Add] para adicionar a camada ao mapa.
Dica
Camadas PostGIS
Normally, a PostGIS layer is defined by an entry in the geometry_columns table. From version 0.9.0 on, QGIS can load layers that do not have an entry in the geometry_columns table. This includes both tables and views. Defining a spatial view provides a powerful means to visualize your data. Refer to your PostgreSQL manual for information on creating views.
The service connection file allows PostgreSQL connection parameters to be associated with a single service name. That service name can then be specified by a client and the associated settings will be used.
It’s called .pg_service.conf under *nix systems (GNU/Linux, macOS etc.) and pg_service.conf on Windows.
The service file looks like:
[water_service]
host=192.168.0.45
port=5433
dbname=gisdb
user=paul
password=paulspass
[wastewater_service]
host=dbserver.com
dbname=water
user=waterpass
Nota
There are two services in the above example: water_service and wastewater_service. You can use these to connect from QGIS, pgAdmin etc. by specifying only the name of the service you want to connect to (without the enclosing brackets). If you want to use the service with psql you need to do something like export PGSERVICE=water_service before doing your psql commands.
Nota
You can find all the parameters here
Nota
If you don’t want to save the passwords in the service file you can use the .pg_pass option.
On *nix operating systems (GNU/Linux, macOS etc.) you can save the .pg_service.conf file in the user’s home directory and the PostgreSQL clients will automatically be aware of it. For example, if the logged user is web, .pg_service.conf should be saved in the /home/web/ directory in order to directly work (without specifying any other environment variables).
You can specify the location of the service file by creating a PGSERVICEFILE environment variable (e.g. run the export PGSERVICEFILE=/home/web/.pg_service.conf command under your *nix OS to temporarily set the PGSERVICEFILE variable)
You can also make the service file available system-wide (all users) either by placing it at pg_config --sysconfdir``**/.pg_service.conf** or by adding the ``PGSYSCONFDIR environment variable to specify the directory containing the service file. If service definitions with the same name exist in the user and the system file, the user file takes precedence.
Aviso
There are some caveats under Windows:
This section contains some details on how QGIS accesses PostgreSQL layers. Most of the time, QGIS should simply provide you with a list of database tables that can be loaded, and it will load them on request. However, if you have trouble loading a PostgreSQL table into QGIS, the information below may help you understand any QGIS messages and give you direction on changing the PostgreSQL table or view definition to allow QGIS to load it.
QGIS requires that PostgreSQL layers contain a column that can be used as a unique key for the layer. For tables, this usually means that the table needs a primary key, or a column with a unique constraint on it. In QGIS, this column needs to be of type int4 (an integer of size 4 bytes). Alternatively, the ctid column can be used as primary key. If a table lacks these items, the oid column will be used instead. Performance will be improved if the column is indexed (note that primary keys are automatically indexed in PostgreSQL).
If the PostgreSQL layer is a view, the same requirement exists, but views do not have primary keys or columns with unique constraints on them. You have to define a primary key field (has to be integer) in the QGIS dialog before you can load the view. If a suitable column does not exist in the view, QGIS will not load the layer. If this occurs, the solution is to alter the view so that it does include a suitable column (a type of integer and either a primary key or with a unique constraint, preferably indexed).
QGIS offers a checkbox Select at id that is activated by default. This option gets the ids without the attributes which is faster in most cases. It can make sense to disable this option when you use expensive views.
Dica
Backup de banco de dados PostGIS com camadas salvas pelo QGIS
If you want to make a backup of your PostGIS database using the pg_dump and pg_restore commands, and the default layer styles as saved by QGIS fail to restore afterwards, you need to set the XML option to DOCUMENT and the restore will work.
QGIS allows to filter features already on server side. Check the
Execute expressions on postgres server-side if
possible (Experimental) checkbox to do so. Only supported expressions will be
sent to the database. Expressions using unsupported operators or functions will
gracefully fallback to local evaluation.
Data can be imported into PostgreSQL/PostGIS using several tools, including the DB Manager plugin and the command line tools shp2pgsql and ogr2ogr.
QGIS comes with a core plugin named DB Manager. It can
be used to load shapefiles and other data formats, and it includes support for
schemas. See section Complemento Gerenciador BD for more information.
PostGIS inclui um utilitário chamado shp2pgsql que pode ser usado para importar arquivos em um banco de dados habilitado para PostGIS. Por exemplo, para importar um arquivo denominado ‘lakes.shp’ em um banco de dados PostgreSQL chamado “gis_data”, use o seguinte comando:
shp2pgsql -s 2964 lakes.shp lakes_new | psql gis_data
Isso cria uma nova camada chamada lakes_new no banco de dados gis_data. A nova camada terá um identificador de referência espacial (SRID) de 2964. Consulte a Seção Trabalhando com Projeções para mais informações sobre os sistemas de referência espacial e projeções.
Dica
Exportando conjuntos de dados do PostGIS
Assim como a ferramenta de importação shp2pgsql, há também uma ferramenta para exportar conjuntos de dados PostGIS como shapefiles: pgsql2shp. Este é enviado dentro de sua distribuição PostGIS.
Além de shp2pgsql e de SPIT existe uma outra ferramenta para a inserção de dados geográficos no PostGIS: ogr2ogr. Essa é parte da instalação do GDAL.
Para importar um shapefile no PostGIS, faça o seguinte :
ogr2ogr -f "PostgreSQL" PG:"dbname=postgis host=myhost.de user=postgres
password=topsecret" alaska.shp
Isto irá importar o shapefile alaska.shp para o banco de dados PostGIS postgis usando o usuário postgres com a senha topsecret no servidor myhost.de.
Note que o OGR deve ser construído com PostgreSQL para suportar PostGIS. Você pode ver isso digitando (in )
ogrinfo --formats | grep -i post
Se você preferir usar o PostgreSQL com o comando COPY em vez do padrão INSERT INTO, você pode exportar a seguinte variável de ambiente (pelo menos disponível em e
):
export PG_USE_COPY=YES
ogr2ogr não cria índices espaciais como shp2pgsl. Você precisa criá-los manualmente, usando o comando SQL CREATE INDEX como um passo extra (como descrito na próxima seção melhorando o Desempenho).
Retrieving features from a PostgreSQL database can be time-consuming, especially over a network. You can improve the drawing performance of PostgreSQL layers by ensuring that a PostGIS spatial index exists on each layer in the database. PostGIS supports creation of a GiST (Generalized Search Tree) index to speed up spatial searches of the data (GiST index information is taken from the PostGIS documentation available at http://postgis.net).
Dica
You can use the DBManager to create an index to your layer. You should first select the layer and click on Table > Edit table, go to Indexes tab and click on [Add spatial index].
A sintaxe para criar um índice GiST é:
CREATE INDEX [indexname] ON [tablename]
USING GIST ( [geometryfield] GIST_GEOMETRY_OPS );
Observe que para grandes tabelas, a criação do índice pode levar um longo tempo. Uma vez que o índice é criado, você deve realizar um VACUUM ANALYZE. Consulte a documentação do PostGIS (PostGIS-PROJECT Referências Bibliográficas e Web) para mais informações.
A seguir um exemplo de criação de um índice GiST:
[email protected]:~/current$ psql gis_data
Welcome to psql 8.3.0, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
gis_data=# CREATE INDEX sidx_alaska_lakes ON alaska_lakes
gis_data-# USING GIST (the_geom GIST_GEOMETRY_OPS);
CREATE INDEX
gis_data=# VACUUM ANALYZE alaska_lakes;
VACUUM
gis_data=# \q
[email protected]:~/current$
Many GIS packages don’t wrap vector maps with a geographic reference system (lat/lon) crossing the 180 degrees longitude line (http://postgis.refractions.net/documentation/manual-2.0/ST_Shift_Longitude.html). As result, if we open such a map in QGIS, we will see two far, distinct locations, that should appear near each other. In Figure_vector_4, the tiny point on the far left of the map canvas (Chatham Islands) should be within the grid, to the right of the New Zealand main islands.
Figure Vector 4:
Map in lat/lon crossing the 180° longitude line
A solução alternativa é transformar os valores de longitude utilizando o PostGIS e a função ST_Shift_Longitude. Esta função lê cada ponto/vértice de cada componente de cada feição em uma geometria e se a longitude é < 0°, ela acrescenta 360° a ela. O resultado é uma versão 0° - 360° dos dados a serem plotados em um mapa centralizado em 180°.
Figure Vector 5:
Importar dados para o PostGIS (Importação de dados no PostgreSQL), utilizando, por exemplo, o complemento “Gerenciador BD”.
Use a interface do PostGIS para emitir o seguinte comando (neste exemplo, “TABELA” é o nome da sua tabela PostGIS): gis_data=# update TABELA set the_geom=ST_Shift_Longitude(the_geom);
Se tudo correu bem, você deve receber uma confirmação sobre o número de feições que foram atualizadas. Então você vai ser capaz de carregar o mapa e ver a diferença (Figura_vetor_5).
The first time you load data from a SpatiaLite
database, begin by clicking on the
Add SpatiaLite Layer toolbar button, or by selecting the
Add SpatiaLite Layer... option
from the Layer menu, or by typing Ctrl+Shift+L.
This will bring up a window that will allow you either to connect to a
SpatiaLite database already known to QGIS, which you can choose from the
drop-down menu, or to define a new connection to a new database. To define a
new connection, click on [New] and use the file browser to point to
your SpatiaLite database, which is a file with a .sqlite extension.
Se você quiser salvar uma camada do vetor para o formato SpatiaLite, você pode fazer isso com um clique direito na legenda. Em seguida, clique em ‘Salvar como...’, defina o nome do arquivo final, e selecione ‘SpatiaLite’ como formato e oSRC. Além disso, você pode selecionar ‘SQLite’ como formato e, em seguida, adicionar “SpatiaLite = SIM” no campo opção da fonte de dados OGR. Isto diz OGR para criar um banco de dados SpatiaLite. Veja também http://www.gdal.org/ogr/drv_sqlite.html.
QGIS also supports editable views in SpatiaLite.
Se você quiser criar uma nova camada SpatiaLite, consulte a seção Criando uma nova camada SpatialLite.
Dica
Gestão complementos de dados SpatiaLite
For SpatiaLite data management, you can also use several Python plugins: QSpatiaLite, SpatiaLite Manager or DB Manager (core plugin, recommended). If necessary, they can be downloaded and installed with the Plugin Installer.
QGIS also provides native MS SQL support. The first
time you load MSSQL Spatial data, begin by clicking on the
Add MSSQL Spatial Layer toolbar button or by
selecting the
Add MSSQL Spatial Layer...
option from the Layer menu, or by typing Ctrl+Shift+M.
The spatial features in Oracle Spatial aid users in managing geographic and location data in a native type within an Oracle database. QGIS now has support for such layers.
The first time you use an Oracle Spatial data source,
you must create a connection to the database that contains the data. Begin by
clicking on the
Add Oracle Spatial Layer toolbar
button, selecting the
Add Oracle
Spatial Layer... option from the Layer menu, or typing
Ctrl+Shift+O. To access the connection manager, click on the [New]
button to display the Create a New Oracle Spatial Connection dialog.
The parameters required for a connection are:
Nome: Um nome para esta conexão. Pode ser o mesmo que base de dados
Base de dados: SID ou SERVICE_NAME da instância Oracle.
Port: número da porta do servidor de banco de dados Oracle. A porta padrão é a 1521.
Usuário: Nome de usuário usado para acessar o banco de dados.
Senha: Senha usada com Nome do Usuário para conectar ao banco de dados.
Opcionalmente, você pode ativar caixas de seleção a seguir:
Salvar Nome de Usuário Indica salvar o nome de usuário do banco de dados na configuração da conexão.
Salvar senha Indica se é para salvar a senha do banco de dados nas configurações de conexão.
: guilabel: Olhe somente na tabela de metadados Restringe as tabelas exibidas para aqueles que estão na visão all_sdo_geom_metadata. Isso pode acelerar a exibição inicial de tabelas espaciais.
Verificar apenas as tabelas do usuário Ao procurar tabelas espaciais, restringir a pesquisa para tabelas que são de propriedade do usuário.
:guilabel: Também lista tabelas sem geometria Indica que tabelas sem geometria também devem ser listados por padrão.
Usar estatísticas das tabelas na camada de metadados Quando a camada está configurada, vários metadados são necessários para a tabela Oracle. Isso inclui informações como o número de linhas da tabela, tipo de geometria e escalas espaciais na coluna de geometria. Se a tabela contiver um grande número de linhas, determinando estes metadados pode ser demorado. Ao ativar esta opção, as seguintes operações de metadados de tabela são feitos: contagem de linhas é determinado a partir do comando all_tables.num_rows. Tabelas com extensões são sempre determinadas com a função SDO_TUNE.EXTENTS_OF, mesmo se um filtro de camada é aplicado. Geometria é determinada a partir das primeiras 100 linhas de não-nulas da tabela.
: guilabel: Somente tipos de geometria existente listar apenas os tipos de geometria existentes e não oferecem para adicionar outros.
Aviso
In the Authentication tab, saving username and password will keep unprotected credentials in the connection configuration. Those credentials will be visible if, for instance, you shared the project file with someone. Therefore, it’s advisable to save your credentials in a Authentication configuration instead (configurations tab). See Sistema de Autenticação for more details.
Uma vez que todos os parâmetros e as opções estão configuradas, você pode testar a conexão clicando no botão [Testar Conexão].
Dica
QGIS Configurações do Usuário e Segurança
Depending on your computing environment, storing passwords in your QGIS settings may be a security risk. Passwords are saved in clear text in the system configuration and in the project files! Your customized settings for QGIS are stored based on the operating system:
Once you have one or more connections defined, you can
load layers from the Oracle database. Of course, this requires having data in
Oracle.
Para carregar uma camada Espacial Oracle, execute os seguintes passos:
Escolha a conexão a partir da lista solta a baixo e clique em [Conectar].
Opcionalmente, use Opções de busca para definir quais recursos serão carregados a partir da camada ou use o botão de [Definir Filtro] para iniciar Ferramenta de Consulta.
Encontre a camada(s) que deseja adicionar na lista de camadas disponíveis.
Selecione-o clicando sobre ele. Você pode selecionar várias camadas, mantendo pressionada Shift enquanto clica. Consulte a seção Query Builder para obter informações sobre o uso de Oracle Consultas para definir a camada.
Clique no botão [Add] para adicionar a camada ao mapa.
Dica
Camada Espacial Oracle
Normalmente, uma camada Espacial Oracle é definida por uma entrada na tabela USER_SDO_METADATA.