2013-02-17 3 views
0

Моя задача - выбрать адрес из моей базы данных и сделать requesto для геокодирования api, чтобы получить lat, lng cordinates адреса. Скоро я получу его, я должен заполнить их в dsatabaseПочему это вызывает у меня исключение слишком много клиентов уже

package com.gismo;

import java.net.*; 
import org.xml.sax.InputSource; 
import org.w3c.dom.*; 
import javax.xml.xpath.*; 
import javax.xml.parsers.DocumentBuilderFactory; 
import java.io.*; 
import java.nio.*; 

import java.io.IOException; 
import java.net.URISyntaxException; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.ResultSetMetaData; 
import java.sql.SQLException; 
import java.sql.Statement; 

import javax.xml.parsers.ParserConfigurationException; 
import javax.xml.xpath.XPathExpressionException; 
import org.xml.sax.SAXException; 

public class TestCon { 
    static String nodeString=""; 
    static String nody=""; 
    //static String[] nodeString={}; 
    static String elementValue = ""; 
    static Connection conn2 = null; 

    private static final String GEOCODE_REQUEST_PREFIX = "http://maps.google.com/maps/api/geocode/xml"; 



    public String _xpath = null; 
    public Document _xml = null; 

    public static void main(String[] args) throws IOException, URISyntaxException, ParserConfigurationException, SAXException, ClassNotFoundException 
    { 
     for (int j=200;j<3000;j++) 

     { 
      Class.forName("org.postgresql.Driver"); 

     try 
     { 
      conn2 = DriverManager.getConnection(
        "jdbc:postgresql://localhost:5432/plovdivbizloca", 
        "postgres", "tan"); 
     } 

     catch (SQLException ex) 
     { 

      ex.printStackTrace(); 
     } 

     Statement mystmt = null; 

     String selectQuery = "SELECT main_office_town, address FROM pl_biz where id="+j; 

     try 
     { 
      mystmt = conn2.createStatement(); 
      ResultSet mysr = mystmt.executeQuery(selectQuery); 

      ResultSetMetaData rsmd = mysr.getMetaData(); 
      int colCount = rsmd.getColumnCount(); 
      int numberrow = 0; 
      elementValue=""; 
      while (mysr.next()) 
      { 

       for (int i = 1; i <= colCount; i++) 
       { 

        elementValue += mysr.getString(i); 
        if (i < colCount) 
         elementValue += ","; 
       } 
       System.out.println(elementValue); 


      } 

     } 
     catch (Exception ex) 
     { 
     } 
     // NEW GEOCODING; 

     String inputQuery, resultXml, urlString, xPathString,xi = null; 
     inputQuery = elementValue; 

     urlString = GEOCODE_REQUEST_PREFIX + "?address=" + URLEncoder.encode(inputQuery, "UTF-8") + "&sensor=false"; 
     System.out.println(urlString); 

     // Convert the string to a URL so we can parse it 
     URL url = new URL(urlString); 


     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     Document geocoderResultDocument = null; 
     try 
     { 
      // open the connection and get results as InputSource. 
      conn.connect(); 
      InputSource geocoderResultInputSource = new InputSource(conn.getInputStream()); 

      // read result and parse into XML Document 
      geocoderResultDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(geocoderResultInputSource); 
     } 
     finally 
     { 
      conn.disconnect(); 
     } 

     // Process the results 
     xPathString = "//GeocodeResponse//location/lat"; 
     NodeList nodes = process(geocoderResultDocument, xPathString); 
     System.out.println ("nodes" +nodes.getLength()); 

     // Print results 
     for (int i = 0; i < nodes.getLength(); i++) 
     { 
      nodeString = nodes.item(i).getTextContent(); 
      // nodeString = nodes(i).getTextContent(); 
      System.out.print("cordinate:" + nodeString); 


     } 
     xi = "//GeocodeResponse//location/lng"; 
     NodeList nodes2 = process(geocoderResultDocument, xi); 
     System.out.println ("nodes length" + nodes2.getLength()); 
     for (int i = 0; i < nodes2.getLength(); i++) 
     { 
      nody = nodes2.item(i).getTextContent(); 
      // nodeString = nodes(i).getTextContent(); 
      System.out.println("cl:" + nody); 


     } 

     PreparedStatement pstmt = null; 
     //console.writeln(nodeString); 
     String insertQuery = "UPDATE pl_biz set long= '" + nody+ "' , lat= '"+nodeString+ "' where id="+j; 

     try 
     { 
      pstmt = conn2.prepareStatement(insertQuery); 

      int rowss = pstmt.executeUpdate(); 
      System.out.println("rowss successfull:" +rowss); 

     } 

     catch (Exception ex) { 

     } 
     System.out.println("j:"+j); 
     } 


    } 

    private void TestCon() { 
    } 

    public static NodeList process(Document xml, String xPathStrings) 
      throws IOException { 

     NodeList result = null; 
     System.out.println(result); 
     System.out.print("Geocode Processor 1.0\n"); 

     XPathFactory factory = XPathFactory.newInstance(); 

     XPath xpath = factory.newXPath(); 

     try { 
      result = (NodeList) xpath.evaluate(xPathStrings, xml, 
        XPathConstants.NODESET); 
     } 
     catch (XPathExpressionException ex) { 
      ex.printStackTrace(); 
     } 
     System.out.println(result); 
     return result; 
    } 



} 
+0

Просто переместите отверстие соединения за пределами цикла 'for', чтобы оно произошло только один раз. –

ответ

1

Вы пробовали явный вызов conn2.close(), когда вы сделали с conn2?

+0

mwhere, чтобы закрыть его - возможно, в конце статьи после обновления или у вас есть предложения –

Смежные вопросы