SlideShare una empresa de Scribd logo
1 de 56
Descargar para leer sin conexión
MySQL Spatial


Airton Lastori
airton.lastori@oracle.com



10-abr-2013
1   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
@MySQLBR                                                            facebook.com/MySQLBR

                                                                                                                                               MySQLBR
                                       meetup.com/MySQL-BR




2   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Alguns clientes MySQL




3   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Alguns clientes MySQL




                                                                   fonte: alexa.com/topsites 30-jan-2013
4   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Alguns clientes MySQL




                                                                                          mysql.com/customers
5   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Alguns clientes MySQL




                                                                                          mysql.com/customers
6   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
MySQL: casos de sucesso

                                                                                                                                               + de 20 indústrias

                                                                                                                                               mysql.com/customers




7   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Evolução da escalabilidade do MySQL



                 2008                                                               2009                                                        2010         2013


              até 4 CPU                                                         até 16 CPU                                                     até 32 CPU   até 48 CPU
              MySQL 5.0                                                         MySQL 5.1                                                      MySQL 5.5    MySQL 5.6

              MySQL AB                                                                  Sun                                                      Oracle




9   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Compromisso Oracle com MySQL Community
       Portfólio disponível para download e uso sob GPL


                                                                                                                    MySQL Database Community Server
                                                                                                                    MySQL Cluster
                                                                                                                    MySQL Workbench
                                                                                                                    MySQL Connectors
                                                                                                                    MySQL Proxy
                                                                                                                    Documentação não GPL
                                                                                                                    Forums, Lists, Bugs, Blogs…

10   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Conectores: amplo suporte a várias linguagens

                                                     Oracle                                                                                              Comunidade

              •      Connector/ODBC                                                                                                             •   PHP
              •      Connector/Net (ADO.NET)                                                                                                    •   Perl
              •      Connector/Python                                                                                                           •   Ruby
              •      Connector/J (JDBC)                                                                                                         •   TCL
              •      Connector/C (C API)                                                                                                        •   Eiffel
              •      Connector/C++ (C++ API)                                                                                                    •   …


                                   dev.mysql.com/doc/refman/5.5/en/connectors-apis.html

11   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
MySQL Enterprise Edition
       Maior produtividade e mitigação de riscos


                                                                                                      Oracle Premier
                                                                                                     Lifetime Support
                                                        MySQL Enterprise                                                             Oracle Product
                                                           Security                                                            Certifications/Integrations

                               MySQL Enterprise                                                                                                   MySQL Enterprise
                                   Audit                                                                                                        Monitor/Query Analyzer

                  MySQL Enterprise                                                                                                                       MySQL Enterprise
                     Scalability                                                                                                                             Backup

               MySQL Enterprise
                                                                                                                                                           MySQL Workbench
               High Availability

12   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Arquitetura MySQL Database
            Suporte às mais
            conhecidas
            plataformas/linguagens
            de desenvolvimento
                                                                                                                                                 Gerenciamento
                                                                                                                                                 eficiente e multi-
     Parsing completo                                                                                                                            thread de sessões
     DML+DDL,
     otimizador,
     baseado em custo,
     caching de queries
     e resultados


     Várias opções de
     Storage Engine                                                                                                                             Opções flexíveis de
     para necessidades                                                                                                                          logging e
     específicas das                                                                                                                            armazenamento
     aplicações                                                                                                                                 físico

13   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Qual Storage Engine usar?
                                                                            MyISAM                                     InnoDB                     Archive          NDB Cluster
      Transações                                                                   ✖                                             ✔                     ✖                  ✔

      Nível de Lock                                                            Tabela                                         Linha                 Tabela               Linha
                                                                       Assíncrona ou                                 Assíncrona ou               Assíncrona ou      Síncrona, Multi-
      Replicação
                                                                       Semi-síncrona                                 Semi-síncrona               Semi-síncrona          master
      Foreign Keys                                                                 ✖                                             ✔                     ✖            a partir da v7.3

      Full-text indexes                                                            ✔                                a partir da v5.6                   ✖                  ✖

      Compressão de dados                                             somente Leitura                                            ✔                     ✔                  ✖

      Caches                                                         somente Índices                               Dados e Índices                     ✖            Dados e Índices
                                                                    Tipos de Dados e                             somente Tipos de               somente Tipos de   somente Tipos de
      Suporte Geospacial
                                                                         Índices                                     Dados                          Dados              Dados
      Limite de
                                                                               256TB                                          64TB                  Ilimitado           384EB
      armazenamento

                                                  dev.mysql.com/doc/refman/5.5/en/storage-engines.html
14   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
MySQL Spatial Extensions



                                       Suporte à geração,
                                  armazenamento e análise de
                                    informações geográficas.


15   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
OpenGIS
       Simple Features Specification for SQL

       Modelo conceitual para dados espaciais / geográficos
          propõe extensões para SGBDs SQL
          padronizado pelo Open Geospatial Consortium
          inclui SQL with Geometry Types, estendendo a linguagem

       MySQL é aderente ao OpenGIS
          implementa um subconjunto dos SQL with Geometry Types
          colunas podem possuir os Tipos Geométricos do OpenGIS
          também estão disponíveis funções geométricas para análise
                                                                                www.opengis.org/docs/99-049.pdf

16   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Terminologia
       OpenGIS Simple Features Specification for SQL

       geographic feature ou geospatial feature ou geometry
           algo com uma localização no mundo
           definido e representado por um ponto ou agregado de pontos
           pode ser uma entity, space, definable location
       entity
           uma montanha, um lago, uma cidade etc
       space
           um distrito municipal, os trópicos etc
       definable location
           um cruzamento entre ruas, etc
17   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
OpenGIS Geometry Model
       Tipos de Dados propostos no SQL with Geometry Types




                                                                                                                                *apenas tipos em negrito podem ser instanciados




18   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
OpenGIS Geometry Model
       Exemplos de utilização dos Tipos de Dados instanciáveis
          Point                                                      Em um mapa mundi, cada Point poderia representar uma cidade.
                                                                     Em um mapa municipal, Points representariam paradas de ônibus.

          Linestring                                                 Em um mapa mundi, poderia representar rios.
                                                                     Em um mapa municipal, poderia representar ruas.
          Polygon                                                    Em um mapa nacional, poderia representar florestas, estados etc.

          MultiPoint                                                 Em um mapa mundi, poderia representar uma cadeia de pequenas ilhas
                                                                     que formam um arquipélogo.
                                                                     Em um mapa municipal, poderia representar pontos de paradas de uma
                                                                     linha de ônibus.
          MultiLineString                                            Em um mapa nacional, poderia representar rodovias federais ou rios
                                                                     conectados.
          MultiPolygon                                               Em um mapa nacional, poderia representar lagos pertencentes ao mesmo
                                                                     sistema hídrico.


19   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
OpenGIS Geometry Model
       Hierarquia das Propriedades – Geometry e Point

                                                          Geometry
                                                 type                                                                                                  Point
                                                 SRID                                                                                           x-coordinate
                                                 coordinates                                                                                    y-coordinate
                                                 interior
                                                                                                                                                dimension = 0
                                                 boundary
                                                                                                                                                boundary = EMPTY
                                                 exterior
                                                 MBR //envelope
                                                 simple
                                                 closed
                                                 empty
                                                 dimension

20   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
OpenGIS Geometry Model
       Formatos de Armazenamento
        WKT (Well-Known Text Format)
                      projetado para transportar dados em ASCII, fácil leitura, por exemplo:
                           POINT(15 20)
                           LINESTRING(0 0, 10 10, 20 25, 50 60)
                           POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))
        WKB (Well-Known Binary Format) OpenGIS e ISO SQL/MM Part 3 Spatial
                      BLOBs contendo dados binários de informações geométricas WKB
                      POINT(1 1) = 0101000000000000000000F03F000000000000F03F
                          1 byte (unsigned) para endianess
                          4 bytes (unsigned) para Tipo de Dado de 1 a 7
                          8 bytes (double-precision IEEE 754) para coordenadas X e Y
21   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Tipos de Dados disponíveis

                GEOMETRY pode armazenar geometrias de qualquer tipo
                POINT
                LINESTRING
                POLYGON

                GEOMETRYCOLLECTION pode armazenar coleções de todos tipos
                MULTIPOINT
                MULTILINESTRING
                MULTIPOLYGON

22   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: criando uma tabela


                                                                                                              mapamundi
                                                                                                                                 cidade




                                                                            CREATE TABLE mapamundi (
                                                                                cidade POINT‫‏‬
                                                                             ) ENGINE=MyISAM;




23   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: alterando uma tabela, adicionar coluna


                                                                                                              mapamundi
                                                                                                         cidade                                 rio




                                                                            ALTER TABLE mapamundi
                                                                                  ADD rio LINESTRING;




24   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: alterando uma tabela, remover colunas


                                                                                                              mapamundi
                                                                                                                            geometria


                                                                            ALTER TABLE mapamundi DROP rio;

                                                                            ALTER TABLE mapamundi
                                                                                  ADD geometria GEOMETRY;

                                                                            ALTER TABLE mapamundi DROP cidade;




25   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Criando objetos com funções WKT
           GeomFromText() ou
           funções específicas para cada Tipo, ex: PointFromText()

       Criando objetos com funções WKB
           GeomFromWKB() ou
           funções específicas para cada Tipo, ex: PointFromWKB()

       Criando objetos com funções específicas do MySQL
           Point(), LineString(), Polygon()
           GeometryCollection(), MultiPoint(), MultiLineString(), MultiPolygon()
26   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: inserindo um Point via WKT

                                                                                                              mapamundi
                                                                                                                            geometria
                                                                                 1                                        POINT(1 1)

                                                                             INSERT INTO mapamundi VALUES (
                                                                                 GeomFromText('POINT(1 1)')
                                                                             );


     ou também…                                                                                                                 ...ou ainda…
       SET @g = 'POINT(1 1)';                                                                                                     INSERT INTO mapamundi VALUES(
       INSERT INTO mapamundi VALUES (                                                                                                 Point(1,1)
           GeomFromText(@g)                                                                                                       );
       );

27   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: removendo um Point


                                                                                                              mapamundi
                                                                                                                            geometria



                                                   DELETE FROM mapamundi
                                                       WHERE geometria = GeomFromText('POINT(1 1)');




28   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: inserindo um Point via WKB


                                                                                                              mapamundi
                                                                                                                            geometria
                                                                                 1                                        POINT(1 1)

                                INSERT INTO mapamundi VALUES (
                                    GeomFromWKB(0x0101000000000000000000F03F000000000000F03F)
                                );




29   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: inserindo um LineString

                                                                                                               mapamundi
                                                                                                                             geometria
                                                                                 1                                        POINT(1 1)
                                                                                 2                  LINESTRING(0 0,1 1,2 2)

     SET @g = 'LINESTRING(0 0,1 1,2 2)';
     INSERT INTO mapamundi VALUES (                                                                                            ou também…
         GeomFromText(@g)
     );                                                                                                                                 SET @g = ‘LINESTRING(0 0,1 1,2 2)';
                                                                                                                                        INSERT INTO mapamundi VALUES (
                                                                                                                                            LineStringFromText(@g)
                                                                                                                                        );


30   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: inserindo um Polygon

                                                                                                            mapamundi
                                                                                                                            geometria
                     1                                                                                                   POINT(1 1)
                     2                                                                             LINESTRING(0 0,1 1,2 2)
                     3                           POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))


              SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))';
              INSERT INTO mapamundi VALUES (GeomFromText(@g));




31   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Criando um BD MySQL Spatial
       Exemplo: consultando registros

                                                                                                            mapamundi
                                                                                                                            geometria
                     1                                                                                                   POINT(1 1)
                     2                                                                             LINESTRING(0 0,1 1,2 2)
                     3                           POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))


              SELECT AsText(geometria) FROM mapamundi;

              SELECT AsBinary(geometria) FROM mapamundi;




32   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Análise de dados com MySQL Spatial
       Funções Disponíveis 1/2

         Conversão
             AsBinary(), AsText(), GeomFromText(), GeomFromWKB()
         Propriedades
             Dimension(), Envelope(), GeometryType(), IsSimple(), SRID()
             X(), Y()
             EndPoint(), GLenght(), NumPoints(), PointN(), StartPoint()
             IsClosed()
             Area(), ExteriorRing(), InteriorRingN(), NumInteriorRings()
             Centroid()
             GeometryN(), NumGeometries()
33   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Análise de dados com MySQL Spatial
       Funções Disponíveis 2/2

         Relações
             MBRContains(), MBRDisjoint(), MBREqual(), MBRIntersects(),
            MBROverlaps(), MBRTouches(), MBRWithin()
             Contains(), Crosses(), Disjoint(), Equals(), Intersects(), Overlaps(),
            Touches(), Within()
             ST_Contains(), ST_Crosses(), ST_Disjoint(), ST_Equals(),
            ST_Intersects(), ST_Overlaps(), ST_Touches, ST_Within()
         Clonagem
             Buffer()


34   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Otimizações nos dados do MySQL Spatial
       Índices SPATIAL para Range Scans
         Criando Índices Spatial
              ALTER TABLE mapamundi CHANGE geometria geometria GEOMETRY NOT NULL;

              CREATE SPATIAL INDEX sp_index ON mapamundi(geometria);



         Usando Índices Spatial em Range Scans
              SET @g = 'POLYGON((0 0,9 0,9 9,0 9,0 0),(5 5,7 5,7 7,5 7, 5 5))';
              SELECT AsText(geometria) FROM mapamundi
                  WHERE MBRContains(GeomFromText(@g),geometria);


                                              …apenas deixe o trabalho de selecionar o índice para o Optimizer!
                                                Use o comando EXPLAIN para confirmar se o índice é utilizado.

35   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Nível de Conformidade do MySQL Spatial com
       OpenGIS
       Funcionalidades não-padronizadas
           Lenght() implementada com o nome GLenght()

       Funcionalidades adicionais
           próximos slides

       Funcionalidades não-implementadas
           próximos slides



36   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Funcionalidades Adicionais do MySQL Spatial não
       definidas pelo OpenGIS
       GeometryCollection(g1,g2,...)
       LineString(pt1,pt2,...)
       MultiLineString(ls1,ls2,...)
       MultiPoint(pt1,pt2,...)
       MultiPolygon(poly1,poly2,...)
       Point(x,y)
       Polygon(ls1,ls2,...)




37   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Funcionalidades definidas pelo OpenGIS e não
       implementadas pelo MySQL
       BdPolyFromText() e BdMPolyFromText()
       BdPolyFromWKB() e BdMPolyFromWKB()
       Boundary()
       Buffer() implementada a partir do MySQL 5.6
       ConvexHull()
       Difference()
       Intersection()
       IsEmpty() e IsRing()
       IsSimple() implementada a partir do MySQL 5.6
       PointOnSurface()
       SymDifference()
       Union
       Metadata Views como GEOMETRY_COLUMNS

38   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Como começar




                      Instalação básica, ambiente de
                             desenvolvimento…

                                                                              ...em 15 minutos, ou menos!


39   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
40   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
No Linux ou Mac, prefira os binários




                                                                       mysql.com/downloads/mysql

41   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Cliente-Servidor



                                                                                                                       Client
                                                                                                            mysql / mysql.exe


                                                                                                                     Server
                                                                                                         mysqld / mysqld.exe




42   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Iniciar ou Parar o servidor MySQL no Windows




          …ou via MySQL Notifier




43   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Iniciar ou Parar o servidor MySQL no Linux

          Iniciar:
          /usr/local/mysql/bin> mysqld_safe --defaults-file=/etc/my.cnf &




          Parar:
          /usr/local/mysql/bin> mysqladmin shutdown




                                         dev.mysql.com/doc/refman/5.5/en/mysqld-safe.html

44   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Primeira conexão
          C:Program FilesMySQLMySQL Server 5.5bin>mysql -uroot -p
          Enter password: ****
          Welcome to the MySQL monitor.                                                    Commands end with ; or g.
          Your MySQL connection id is 8
          Server version: 5.6.11 MySQL Community Server (GPL)


          Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.


          Oracle is a registered trademark of Oracle Corporation and/or its
          affiliates. Other names may be trademarks of their respective
          owners.


          Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.


          mysql>



45   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Teste via MySQL Workbench 1/2




46   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Teste via MySQL Workbench 2/2




47   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Cliente-Servidor



                                                                                                     App + Connector
                                                            JDBC, ODBC, .Net, PHP, Python, Perl, Ruby, Native C API…


                                                                                                                         Server
                                                                                                            mysqld / mysqld.exe




48   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Mãos à obra!




                                                                            Hello World…


                                                                                                             ...em Java


49   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Adicione o driver MySQL ao CLASSPATH
           caminho completo do .jar




             Confira:
               C:>set CLASSPATH
               CLASSPATH=.;C:Program Files (x86)Javajre6libextQTJava.zip;C:Program
                 FilesMySQLmysql-connector-java-5.1.22mysql-connector-java-5.1.22-bin.jar




50   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
HelloMysql.java 1/2
              import java.sql.*;
              public class HelloMysql {
                 public static void main(String args[]){
                 System.out.println("Tentando conectar ao MySQL...");
                 try {
                        Class.forName("com.mysql.jdbc.Driver");
                        String url = "jdbc:mysql://localhost:3306/mysql";
                        String usuario = "root";
                        String senha = "root";
                        Connection con = DriverManager.getConnection(url, usuario, senha);
                        System.out.println("URL: " + url);
                        System.out.println("Connection: " + con);
                                                                                                                                                Continua…
51   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
HelloMysql.java 2/2
                        Statement stmt = con.createStatement();                                                                                 //objeto Statement
                        ResultSet rs;                                           //objeto ResultSet
                        rs = stmt.executeQuery("SELECT * FROM world.country");
                        System.out.println("Ola mundo!");
                        while(rs.next()){
                   String nomePais = rs.getString("Name");
                           System.out.print(nomePais + ", ");
                        }//end while
                        con.close();
                    } catch( Exception e ) {
                        e.printStackTrace();
                    }//end catch
                 }//end main
              }//end class HelloMysql
                                                                                                                                                              PRONTO!
52   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
java HelloMysql
            C:tutorial>javac HelloMysql.java


            C:tutorial>java HelloMysql
            Tentando conectar ao MySQL...
            URL: jdbc:mysql://localhost:3306/mysql
            Connection: com.mysql.jdbc.JDBC4Connection@ed07f45
            Ola mundo!
            Aruba, Afghanistan, Angola, Anguilla, Albania, Andorra, Netherlands Antilles, Un
            ited Arab Emirates, Argentina, Armenia, American Samoa, Antarctica, French South
            ern territories, Antigua and Barbuda, Australia, Austria, Azerbaijan, Burundi, B
            elgium, Benin, Burkina Faso, Bangladesh, Bulgaria, Bahrain, Bahamas, Bosnia and
            Herzegovina, Belarus, Belize, Bermuda, Bolivia, Brazil, Barbados, Brunei, Bhutan
            …
            ietnam, Vanuatu, Wallis and Futuna, Samoa, Yemen, Yugoslavia, South Africa, Zamb
            ia, Zimbabwe,



53   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Próximo passo: documentação

          Reference Manual
                    1. Tutorial
                    2. SQL Syntax
                    3. Connectors & APIs, Memcached
                    4. MySQL Spatial Extensions
                    5. Functions, Views, Stored Programs
                    6. Optimization

                                                    dev.mysql.com/doc/refman/5.5/en/index.html

54   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Sumário

                   O MySQL é o banco de dados open source mais popular do
                    mundo, usado em grandes sites, aplicações mobile, embarcadas
                    e sistemas de informações geográficas.
                   Possui amplo suporte ao modelo OpenGIS, principalmente no
                    Storage Engine MyISAM.
                   Instale e comece a usar em menos de 15min. Use e abuse da
                    documentação!



55   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
@MySQLBR                                                            facebook.com/MySQLBR

                                                                                                                                                Obrigado!
                                        meetup.com/MySQL-BR




56   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
MySQL Spatial


Perguntas?


57   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12

Más contenido relacionado

La actualidad más candente

Oracle backup and recovery
Oracle backup and recoveryOracle backup and recovery
Oracle backup and recovery
Yogiji Creations
 
lamp technology
lamp technologylamp technology
lamp technology
Deepa
 

La actualidad más candente (20)

Database security
Database securityDatabase security
Database security
 
Oracle Cloud is Best for Oracle Database - High Availability
Oracle Cloud is Best for Oracle Database - High AvailabilityOracle Cloud is Best for Oracle Database - High Availability
Oracle Cloud is Best for Oracle Database - High Availability
 
Oracle backup and recovery
Oracle backup and recoveryOracle backup and recovery
Oracle backup and recovery
 
Hadoop & Greenplum: Why Do Such a Thing?
Hadoop & Greenplum: Why Do Such a Thing?Hadoop & Greenplum: Why Do Such a Thing?
Hadoop & Greenplum: Why Do Such a Thing?
 
Desktop Support Engineer Interview Questions & Answers
Desktop Support Engineer Interview Questions & Answers Desktop Support Engineer Interview Questions & Answers
Desktop Support Engineer Interview Questions & Answers
 
Oracle Architecture
Oracle ArchitectureOracle Architecture
Oracle Architecture
 
lamp technology
lamp technologylamp technology
lamp technology
 
DRaaS on Microsoft Azure with Veeam Software
DRaaS on Microsoft Azure with Veeam SoftwareDRaaS on Microsoft Azure with Veeam Software
DRaaS on Microsoft Azure with Veeam Software
 
Oracle User Management
Oracle User ManagementOracle User Management
Oracle User Management
 
Database management system by Gursharan singh
Database management system by Gursharan singhDatabase management system by Gursharan singh
Database management system by Gursharan singh
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)
 
Power BI Tutorial For Beginners | Power BI Tutorial | Power BI Demo | Power B...
Power BI Tutorial For Beginners | Power BI Tutorial | Power BI Demo | Power B...Power BI Tutorial For Beginners | Power BI Tutorial | Power BI Demo | Power B...
Power BI Tutorial For Beginners | Power BI Tutorial | Power BI Demo | Power B...
 
Oracle Real Application Clusters (RAC) 12c Rel. 2 - Operational Best Practices
Oracle Real Application Clusters (RAC) 12c Rel. 2 - Operational Best PracticesOracle Real Application Clusters (RAC) 12c Rel. 2 - Operational Best Practices
Oracle Real Application Clusters (RAC) 12c Rel. 2 - Operational Best Practices
 
Power BI Desktop | Power BI Tutorial | Power BI Training | Edureka
Power BI Desktop | Power BI Tutorial | Power BI Training | EdurekaPower BI Desktop | Power BI Tutorial | Power BI Training | Edureka
Power BI Desktop | Power BI Tutorial | Power BI Training | Edureka
 
MySQL Multi Master Replication
MySQL Multi Master ReplicationMySQL Multi Master Replication
MySQL Multi Master Replication
 
Database backup & recovery
Database backup & recoveryDatabase backup & recovery
Database backup & recovery
 
EMEA Airheads- Instant AP- Instant AP Best Practice Configuration
EMEA Airheads- Instant AP- Instant AP Best Practice ConfigurationEMEA Airheads- Instant AP- Instant AP Best Practice Configuration
EMEA Airheads- Instant AP- Instant AP Best Practice Configuration
 
EL ANTIVIRUS
EL ANTIVIRUSEL ANTIVIRUS
EL ANTIVIRUS
 
Relational database management system (rdbms) i
Relational database management system (rdbms) iRelational database management system (rdbms) i
Relational database management system (rdbms) i
 
AV/DF Advanced Security Option
AV/DF Advanced Security OptionAV/DF Advanced Security Option
AV/DF Advanced Security Option
 

Similar a MySQL Spatial

What is new in MySQL? (Lars Thalmann)
What is new in MySQL? (Lars Thalmann)What is new in MySQL? (Lars Thalmann)
What is new in MySQL? (Lars Thalmann)
Ontico
 
Oracle to MySQL 2012
Oracle to MySQL  2012 Oracle to MySQL  2012
Oracle to MySQL 2012
Marco Tusa
 
UKOUG 2011: MySQL Architectures for Oracle DBA's
UKOUG 2011: MySQL Architectures for Oracle DBA'sUKOUG 2011: MySQL Architectures for Oracle DBA's
UKOUG 2011: MySQL Architectures for Oracle DBA's
FromDual GmbH
 
Santo Leto - MySQL Connect 2012 - Getting Started with Mysql Cluster
Santo Leto - MySQL Connect 2012 - Getting Started with Mysql ClusterSanto Leto - MySQL Connect 2012 - Getting Started with Mysql Cluster
Santo Leto - MySQL Connect 2012 - Getting Started with Mysql Cluster
Santo Leto
 
Oracle my sql cluster cge
Oracle my sql cluster cgeOracle my sql cluster cge
Oracle my sql cluster cge
seungdon1
 

Similar a MySQL Spatial (20)

MySQL para Desenvolvedores
MySQL para DesenvolvedoresMySQL para Desenvolvedores
MySQL para Desenvolvedores
 
MySQL para Desenvolvedores de Games
MySQL para Desenvolvedores de GamesMySQL para Desenvolvedores de Games
MySQL para Desenvolvedores de Games
 
Posscon my sql56
Posscon my sql56Posscon my sql56
Posscon my sql56
 
MySQL 8: Ready for Prime Time
MySQL 8: Ready for Prime TimeMySQL 8: Ready for Prime Time
MySQL 8: Ready for Prime Time
 
What is new in MySQL? (Lars Thalmann)
What is new in MySQL? (Lars Thalmann)What is new in MySQL? (Lars Thalmann)
What is new in MySQL? (Lars Thalmann)
 
MySQL Connector/J in the Making of Modern Applications
MySQL Connector/J in the Making of Modern ApplicationsMySQL Connector/J in the Making of Modern Applications
MySQL Connector/J in the Making of Modern Applications
 
NoSQL and MySQL
NoSQL and MySQLNoSQL and MySQL
NoSQL and MySQL
 
MySQL 20 años: pasado, presente y futuro; conoce las nuevas características d...
MySQL 20 años: pasado, presente y futuro; conoce las nuevas características d...MySQL 20 años: pasado, presente y futuro; conoce las nuevas características d...
MySQL 20 años: pasado, presente y futuro; conoce las nuevas características d...
 
MySQL Community and Commercial Edition
MySQL Community and Commercial EditionMySQL Community and Commercial Edition
MySQL Community and Commercial Edition
 
MySQL For Oracle Developers
MySQL For Oracle DevelopersMySQL For Oracle Developers
MySQL For Oracle Developers
 
Simple Way for MySQL to NoSQL
Simple Way for MySQL to NoSQLSimple Way for MySQL to NoSQL
Simple Way for MySQL to NoSQL
 
Sunshine php my sql 8.0 v2
Sunshine php my sql 8.0 v2Sunshine php my sql 8.0 v2
Sunshine php my sql 8.0 v2
 
My sql susecon_crashcourse_2012
My sql susecon_crashcourse_2012My sql susecon_crashcourse_2012
My sql susecon_crashcourse_2012
 
MySQL
MySQLMySQL
MySQL
 
Oracle to MySQL 2012
Oracle to MySQL  2012 Oracle to MySQL  2012
Oracle to MySQL 2012
 
UKOUG 2011: MySQL Architectures for Oracle DBA's
UKOUG 2011: MySQL Architectures for Oracle DBA'sUKOUG 2011: MySQL Architectures for Oracle DBA's
UKOUG 2011: MySQL Architectures for Oracle DBA's
 
Santo Leto - MySQL Connect 2012 - Getting Started with Mysql Cluster
Santo Leto - MySQL Connect 2012 - Getting Started with Mysql ClusterSanto Leto - MySQL Connect 2012 - Getting Started with Mysql Cluster
Santo Leto - MySQL Connect 2012 - Getting Started with Mysql Cluster
 
20191001 bkk-secret-of inno-db_clusterv1
20191001 bkk-secret-of inno-db_clusterv120191001 bkk-secret-of inno-db_clusterv1
20191001 bkk-secret-of inno-db_clusterv1
 
My sql crashcourse_2012
My sql crashcourse_2012My sql crashcourse_2012
My sql crashcourse_2012
 
Oracle my sql cluster cge
Oracle my sql cluster cgeOracle my sql cluster cge
Oracle my sql cluster cge
 

Más de MySQL Brasil

Más de MySQL Brasil (20)

MySQL como Document Store PHP Conference 2017
MySQL como Document Store PHP Conference 2017MySQL como Document Store PHP Conference 2017
MySQL como Document Store PHP Conference 2017
 
MySQL no Paypal Tesla e Uber
MySQL no Paypal Tesla e UberMySQL no Paypal Tesla e Uber
MySQL no Paypal Tesla e Uber
 
MySQL 8.0.1 DMR
MySQL 8.0.1 DMRMySQL 8.0.1 DMR
MySQL 8.0.1 DMR
 
Alta disponibilidade com MySQL Enterprise
Alta disponibilidade com MySQL EnterpriseAlta disponibilidade com MySQL Enterprise
Alta disponibilidade com MySQL Enterprise
 
MySQL Roadmap NoSQL HA Fev17
MySQL Roadmap NoSQL HA Fev17MySQL Roadmap NoSQL HA Fev17
MySQL Roadmap NoSQL HA Fev17
 
Segurança no MySQL
Segurança no MySQLSegurança no MySQL
Segurança no MySQL
 
5 razões estratégicas para usar MySQL
5 razões estratégicas para usar MySQL5 razões estratégicas para usar MySQL
5 razões estratégicas para usar MySQL
 
Alta disponibilidade no MySQL 5.7 GUOB 2016
Alta disponibilidade no MySQL 5.7 GUOB 2016Alta disponibilidade no MySQL 5.7 GUOB 2016
Alta disponibilidade no MySQL 5.7 GUOB 2016
 
MySQL 5.7 como Document Store
MySQL 5.7 como Document StoreMySQL 5.7 como Document Store
MySQL 5.7 como Document Store
 
Enabling digital transformation with MySQL
Enabling digital transformation with MySQLEnabling digital transformation with MySQL
Enabling digital transformation with MySQL
 
Alta Disponibilidade no MySQL 5.7 para aplicações em PHP
Alta Disponibilidade no MySQL 5.7 para aplicações em PHPAlta Disponibilidade no MySQL 5.7 para aplicações em PHP
Alta Disponibilidade no MySQL 5.7 para aplicações em PHP
 
Alta Disponibilidade no MySQL 5.7
Alta Disponibilidade no MySQL 5.7Alta Disponibilidade no MySQL 5.7
Alta Disponibilidade no MySQL 5.7
 
NoSQL no MySQL 5.7
NoSQL no MySQL 5.7NoSQL no MySQL 5.7
NoSQL no MySQL 5.7
 
OpenStack & MySQL
OpenStack & MySQLOpenStack & MySQL
OpenStack & MySQL
 
10 Razões para Usar MySQL em Startups
10 Razões para Usar MySQL em Startups10 Razões para Usar MySQL em Startups
10 Razões para Usar MySQL em Startups
 
Novidades do MySQL para desenvolvedores ago15
Novidades do MySQL para desenvolvedores ago15Novidades do MySQL para desenvolvedores ago15
Novidades do MySQL para desenvolvedores ago15
 
Estratégias de Segurança e Gerenciamento para MySQL
Estratégias de Segurança e Gerenciamento para MySQLEstratégias de Segurança e Gerenciamento para MySQL
Estratégias de Segurança e Gerenciamento para MySQL
 
Novidades do Universo MySQL julho-15
Novidades do Universo MySQL julho-15Novidades do Universo MySQL julho-15
Novidades do Universo MySQL julho-15
 
Serviços Escaláveis e de Alta Performance com MySQL e Java
Serviços Escaláveis e de Alta Performance com MySQL e JavaServiços Escaláveis e de Alta Performance com MySQL e Java
Serviços Escaláveis e de Alta Performance com MySQL e Java
 
MySQL The State of the Dolphin - jun15
MySQL The State of the Dolphin - jun15MySQL The State of the Dolphin - jun15
MySQL The State of the Dolphin - jun15
 

MySQL Spatial

  • 1. MySQL Spatial Airton Lastori airton.lastori@oracle.com 10-abr-2013 1 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 2. @MySQLBR facebook.com/MySQLBR MySQLBR meetup.com/MySQL-BR 2 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 3. Alguns clientes MySQL 3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 4. Alguns clientes MySQL fonte: alexa.com/topsites 30-jan-2013 4 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 5. Alguns clientes MySQL mysql.com/customers 5 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 6. Alguns clientes MySQL mysql.com/customers 6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 7. MySQL: casos de sucesso + de 20 indústrias mysql.com/customers 7 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 8. Evolução da escalabilidade do MySQL 2008 2009 2010 2013 até 4 CPU até 16 CPU até 32 CPU até 48 CPU MySQL 5.0 MySQL 5.1 MySQL 5.5 MySQL 5.6 MySQL AB Sun Oracle 9 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 9. Compromisso Oracle com MySQL Community Portfólio disponível para download e uso sob GPL  MySQL Database Community Server  MySQL Cluster  MySQL Workbench  MySQL Connectors  MySQL Proxy  Documentação não GPL  Forums, Lists, Bugs, Blogs… 10 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 10. Conectores: amplo suporte a várias linguagens Oracle Comunidade • Connector/ODBC • PHP • Connector/Net (ADO.NET) • Perl • Connector/Python • Ruby • Connector/J (JDBC) • TCL • Connector/C (C API) • Eiffel • Connector/C++ (C++ API) • … dev.mysql.com/doc/refman/5.5/en/connectors-apis.html 11 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 11. MySQL Enterprise Edition Maior produtividade e mitigação de riscos Oracle Premier Lifetime Support MySQL Enterprise Oracle Product Security Certifications/Integrations MySQL Enterprise MySQL Enterprise Audit Monitor/Query Analyzer MySQL Enterprise MySQL Enterprise Scalability Backup MySQL Enterprise MySQL Workbench High Availability 12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 12. Arquitetura MySQL Database Suporte às mais conhecidas plataformas/linguagens de desenvolvimento Gerenciamento eficiente e multi- Parsing completo thread de sessões DML+DDL, otimizador, baseado em custo, caching de queries e resultados Várias opções de Storage Engine Opções flexíveis de para necessidades logging e específicas das armazenamento aplicações físico 13 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 13. Qual Storage Engine usar? MyISAM InnoDB Archive NDB Cluster Transações ✖ ✔ ✖ ✔ Nível de Lock Tabela Linha Tabela Linha Assíncrona ou Assíncrona ou Assíncrona ou Síncrona, Multi- Replicação Semi-síncrona Semi-síncrona Semi-síncrona master Foreign Keys ✖ ✔ ✖ a partir da v7.3 Full-text indexes ✔ a partir da v5.6 ✖ ✖ Compressão de dados somente Leitura ✔ ✔ ✖ Caches somente Índices Dados e Índices ✖ Dados e Índices Tipos de Dados e somente Tipos de somente Tipos de somente Tipos de Suporte Geospacial Índices Dados Dados Dados Limite de 256TB 64TB Ilimitado 384EB armazenamento dev.mysql.com/doc/refman/5.5/en/storage-engines.html 14 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 14. MySQL Spatial Extensions Suporte à geração, armazenamento e análise de informações geográficas. 15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 15. OpenGIS Simple Features Specification for SQL  Modelo conceitual para dados espaciais / geográficos  propõe extensões para SGBDs SQL  padronizado pelo Open Geospatial Consortium  inclui SQL with Geometry Types, estendendo a linguagem  MySQL é aderente ao OpenGIS  implementa um subconjunto dos SQL with Geometry Types  colunas podem possuir os Tipos Geométricos do OpenGIS  também estão disponíveis funções geométricas para análise www.opengis.org/docs/99-049.pdf 16 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 16. Terminologia OpenGIS Simple Features Specification for SQL  geographic feature ou geospatial feature ou geometry  algo com uma localização no mundo  definido e representado por um ponto ou agregado de pontos  pode ser uma entity, space, definable location  entity  uma montanha, um lago, uma cidade etc  space  um distrito municipal, os trópicos etc  definable location  um cruzamento entre ruas, etc 17 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 17. OpenGIS Geometry Model Tipos de Dados propostos no SQL with Geometry Types *apenas tipos em negrito podem ser instanciados 18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 18. OpenGIS Geometry Model Exemplos de utilização dos Tipos de Dados instanciáveis Point Em um mapa mundi, cada Point poderia representar uma cidade. Em um mapa municipal, Points representariam paradas de ônibus. Linestring Em um mapa mundi, poderia representar rios. Em um mapa municipal, poderia representar ruas. Polygon Em um mapa nacional, poderia representar florestas, estados etc. MultiPoint Em um mapa mundi, poderia representar uma cadeia de pequenas ilhas que formam um arquipélogo. Em um mapa municipal, poderia representar pontos de paradas de uma linha de ônibus. MultiLineString Em um mapa nacional, poderia representar rodovias federais ou rios conectados. MultiPolygon Em um mapa nacional, poderia representar lagos pertencentes ao mesmo sistema hídrico. 19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 19. OpenGIS Geometry Model Hierarquia das Propriedades – Geometry e Point Geometry type Point SRID x-coordinate coordinates y-coordinate interior dimension = 0 boundary boundary = EMPTY exterior MBR //envelope simple closed empty dimension 20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 20. OpenGIS Geometry Model Formatos de Armazenamento  WKT (Well-Known Text Format)  projetado para transportar dados em ASCII, fácil leitura, por exemplo:  POINT(15 20)  LINESTRING(0 0, 10 10, 20 25, 50 60)  POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))  WKB (Well-Known Binary Format) OpenGIS e ISO SQL/MM Part 3 Spatial  BLOBs contendo dados binários de informações geométricas WKB  POINT(1 1) = 0101000000000000000000F03F000000000000F03F  1 byte (unsigned) para endianess  4 bytes (unsigned) para Tipo de Dado de 1 a 7  8 bytes (double-precision IEEE 754) para coordenadas X e Y 21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 21. Criando um BD MySQL Spatial Tipos de Dados disponíveis  GEOMETRY pode armazenar geometrias de qualquer tipo  POINT  LINESTRING  POLYGON  GEOMETRYCOLLECTION pode armazenar coleções de todos tipos  MULTIPOINT  MULTILINESTRING  MULTIPOLYGON 22 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 22. Criando um BD MySQL Spatial Exemplo: criando uma tabela mapamundi cidade CREATE TABLE mapamundi ( cidade POINT‫‏‬ ) ENGINE=MyISAM; 23 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 23. Criando um BD MySQL Spatial Exemplo: alterando uma tabela, adicionar coluna mapamundi cidade rio ALTER TABLE mapamundi ADD rio LINESTRING; 24 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 24. Criando um BD MySQL Spatial Exemplo: alterando uma tabela, remover colunas mapamundi geometria ALTER TABLE mapamundi DROP rio; ALTER TABLE mapamundi ADD geometria GEOMETRY; ALTER TABLE mapamundi DROP cidade; 25 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 25. Criando um BD MySQL Spatial  Criando objetos com funções WKT  GeomFromText() ou  funções específicas para cada Tipo, ex: PointFromText()  Criando objetos com funções WKB  GeomFromWKB() ou  funções específicas para cada Tipo, ex: PointFromWKB()  Criando objetos com funções específicas do MySQL  Point(), LineString(), Polygon()  GeometryCollection(), MultiPoint(), MultiLineString(), MultiPolygon() 26 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 26. Criando um BD MySQL Spatial Exemplo: inserindo um Point via WKT mapamundi geometria 1 POINT(1 1) INSERT INTO mapamundi VALUES ( GeomFromText('POINT(1 1)') ); ou também… ...ou ainda… SET @g = 'POINT(1 1)'; INSERT INTO mapamundi VALUES( INSERT INTO mapamundi VALUES ( Point(1,1) GeomFromText(@g) ); ); 27 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 27. Criando um BD MySQL Spatial Exemplo: removendo um Point mapamundi geometria DELETE FROM mapamundi WHERE geometria = GeomFromText('POINT(1 1)'); 28 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 28. Criando um BD MySQL Spatial Exemplo: inserindo um Point via WKB mapamundi geometria 1 POINT(1 1) INSERT INTO mapamundi VALUES ( GeomFromWKB(0x0101000000000000000000F03F000000000000F03F) ); 29 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 29. Criando um BD MySQL Spatial Exemplo: inserindo um LineString mapamundi geometria 1 POINT(1 1) 2 LINESTRING(0 0,1 1,2 2) SET @g = 'LINESTRING(0 0,1 1,2 2)'; INSERT INTO mapamundi VALUES ( ou também… GeomFromText(@g) ); SET @g = ‘LINESTRING(0 0,1 1,2 2)'; INSERT INTO mapamundi VALUES ( LineStringFromText(@g) ); 30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 30. Criando um BD MySQL Spatial Exemplo: inserindo um Polygon mapamundi geometria 1 POINT(1 1) 2 LINESTRING(0 0,1 1,2 2) 3 POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5)) SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))'; INSERT INTO mapamundi VALUES (GeomFromText(@g)); 31 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 31. Criando um BD MySQL Spatial Exemplo: consultando registros mapamundi geometria 1 POINT(1 1) 2 LINESTRING(0 0,1 1,2 2) 3 POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5)) SELECT AsText(geometria) FROM mapamundi; SELECT AsBinary(geometria) FROM mapamundi; 32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 32. Análise de dados com MySQL Spatial Funções Disponíveis 1/2  Conversão  AsBinary(), AsText(), GeomFromText(), GeomFromWKB()  Propriedades  Dimension(), Envelope(), GeometryType(), IsSimple(), SRID()  X(), Y()  EndPoint(), GLenght(), NumPoints(), PointN(), StartPoint()  IsClosed()  Area(), ExteriorRing(), InteriorRingN(), NumInteriorRings()  Centroid()  GeometryN(), NumGeometries() 33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 33. Análise de dados com MySQL Spatial Funções Disponíveis 2/2  Relações  MBRContains(), MBRDisjoint(), MBREqual(), MBRIntersects(), MBROverlaps(), MBRTouches(), MBRWithin()  Contains(), Crosses(), Disjoint(), Equals(), Intersects(), Overlaps(), Touches(), Within()  ST_Contains(), ST_Crosses(), ST_Disjoint(), ST_Equals(), ST_Intersects(), ST_Overlaps(), ST_Touches, ST_Within()  Clonagem  Buffer() 34 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 34. Otimizações nos dados do MySQL Spatial Índices SPATIAL para Range Scans  Criando Índices Spatial ALTER TABLE mapamundi CHANGE geometria geometria GEOMETRY NOT NULL; CREATE SPATIAL INDEX sp_index ON mapamundi(geometria);  Usando Índices Spatial em Range Scans SET @g = 'POLYGON((0 0,9 0,9 9,0 9,0 0),(5 5,7 5,7 7,5 7, 5 5))'; SELECT AsText(geometria) FROM mapamundi WHERE MBRContains(GeomFromText(@g),geometria); …apenas deixe o trabalho de selecionar o índice para o Optimizer! Use o comando EXPLAIN para confirmar se o índice é utilizado. 35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 35. Nível de Conformidade do MySQL Spatial com OpenGIS  Funcionalidades não-padronizadas  Lenght() implementada com o nome GLenght()  Funcionalidades adicionais  próximos slides  Funcionalidades não-implementadas  próximos slides 36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 36. Funcionalidades Adicionais do MySQL Spatial não definidas pelo OpenGIS  GeometryCollection(g1,g2,...)  LineString(pt1,pt2,...)  MultiLineString(ls1,ls2,...)  MultiPoint(pt1,pt2,...)  MultiPolygon(poly1,poly2,...)  Point(x,y)  Polygon(ls1,ls2,...) 37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 37. Funcionalidades definidas pelo OpenGIS e não implementadas pelo MySQL  BdPolyFromText() e BdMPolyFromText()  BdPolyFromWKB() e BdMPolyFromWKB()  Boundary()  Buffer() implementada a partir do MySQL 5.6  ConvexHull()  Difference()  Intersection()  IsEmpty() e IsRing()  IsSimple() implementada a partir do MySQL 5.6  PointOnSurface()  SymDifference()  Union  Metadata Views como GEOMETRY_COLUMNS 38 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 38. Como começar Instalação básica, ambiente de desenvolvimento… ...em 15 minutos, ou menos! 39 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 39. 40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 40. No Linux ou Mac, prefira os binários mysql.com/downloads/mysql 41 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 41. Cliente-Servidor Client mysql / mysql.exe Server mysqld / mysqld.exe 42 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 42. Iniciar ou Parar o servidor MySQL no Windows …ou via MySQL Notifier 43 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 43. Iniciar ou Parar o servidor MySQL no Linux Iniciar: /usr/local/mysql/bin> mysqld_safe --defaults-file=/etc/my.cnf & Parar: /usr/local/mysql/bin> mysqladmin shutdown dev.mysql.com/doc/refman/5.5/en/mysqld-safe.html 44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 44. Primeira conexão C:Program FilesMySQLMySQL Server 5.5bin>mysql -uroot -p Enter password: **** Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 8 Server version: 5.6.11 MySQL Community Server (GPL) Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement. mysql> 45 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 45. Teste via MySQL Workbench 1/2 46 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 46. Teste via MySQL Workbench 2/2 47 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 47. Cliente-Servidor App + Connector JDBC, ODBC, .Net, PHP, Python, Perl, Ruby, Native C API… Server mysqld / mysqld.exe 48 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 48. Mãos à obra! Hello World… ...em Java 49 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 49. Adicione o driver MySQL ao CLASSPATH caminho completo do .jar Confira: C:>set CLASSPATH CLASSPATH=.;C:Program Files (x86)Javajre6libextQTJava.zip;C:Program FilesMySQLmysql-connector-java-5.1.22mysql-connector-java-5.1.22-bin.jar 50 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 50. HelloMysql.java 1/2 import java.sql.*; public class HelloMysql { public static void main(String args[]){ System.out.println("Tentando conectar ao MySQL..."); try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; String usuario = "root"; String senha = "root"; Connection con = DriverManager.getConnection(url, usuario, senha); System.out.println("URL: " + url); System.out.println("Connection: " + con); Continua… 51 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 51. HelloMysql.java 2/2 Statement stmt = con.createStatement(); //objeto Statement ResultSet rs; //objeto ResultSet rs = stmt.executeQuery("SELECT * FROM world.country"); System.out.println("Ola mundo!"); while(rs.next()){ String nomePais = rs.getString("Name"); System.out.print(nomePais + ", "); }//end while con.close(); } catch( Exception e ) { e.printStackTrace(); }//end catch }//end main }//end class HelloMysql PRONTO! 52 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 52. java HelloMysql C:tutorial>javac HelloMysql.java C:tutorial>java HelloMysql Tentando conectar ao MySQL... URL: jdbc:mysql://localhost:3306/mysql Connection: com.mysql.jdbc.JDBC4Connection@ed07f45 Ola mundo! Aruba, Afghanistan, Angola, Anguilla, Albania, Andorra, Netherlands Antilles, Un ited Arab Emirates, Argentina, Armenia, American Samoa, Antarctica, French South ern territories, Antigua and Barbuda, Australia, Austria, Azerbaijan, Burundi, B elgium, Benin, Burkina Faso, Bangladesh, Bulgaria, Bahrain, Bahamas, Bosnia and Herzegovina, Belarus, Belize, Bermuda, Bolivia, Brazil, Barbados, Brunei, Bhutan … ietnam, Vanuatu, Wallis and Futuna, Samoa, Yemen, Yugoslavia, South Africa, Zamb ia, Zimbabwe, 53 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 53. Próximo passo: documentação Reference Manual 1. Tutorial 2. SQL Syntax 3. Connectors & APIs, Memcached 4. MySQL Spatial Extensions 5. Functions, Views, Stored Programs 6. Optimization dev.mysql.com/doc/refman/5.5/en/index.html 54 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 54. Sumário  O MySQL é o banco de dados open source mais popular do mundo, usado em grandes sites, aplicações mobile, embarcadas e sistemas de informações geográficas.  Possui amplo suporte ao modelo OpenGIS, principalmente no Storage Engine MyISAM.  Instale e comece a usar em menos de 15min. Use e abuse da documentação! 55 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 55. @MySQLBR facebook.com/MySQLBR Obrigado! meetup.com/MySQL-BR 56 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 56. MySQL Spatial Perguntas? 57 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12