3 Replies Latest reply: Sep 12, 2008 5:31 PM by 807589 RSS

    MySQL db and JAVA quick questio about connections

    807589
      I get this error sometimes I think because I am accessing the database so many times in a row. When is the optimal time to close the connectio and re open it? Should I open it and close it for each query in the loop, or just open at the start and close at the end?:

      {color:#ff0000}Cannot connect to MySQL server on localhost:3306. Is there a MySQL server running on the machine/port you are trying to connect to? (java.net.BindException)
      Got an exception!{color}

      *{color:#000000}When I run this code{color}*


      for(int i=0; i<cleanedWords.size(); i++)
      createCharacteristicArray(cleanedWords.get(i));



      try{
      connection.close();
      } catch (Exception e) {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
      }


      private void createCharacteristicArray(String current);

      String strt = "";
      int Large = 0;

      try{

      Class.forName ("org.gjt.mm.mysql.Driver").newInstance ();
      String dbURL = "jdbc:mysql://localhost/MusicWords";
      String u = "root";
      String p ="";
      connection = DriverManager.getConnection(dbURL, u, p);
      Statement statement = connection.createStatement();
      ResultSet result = null;

      // 1. Select Statement
      String preparedSelect = "SELECT * FROM main WHERE word = ?";
      PreparedStatement ps = connection.prepareStatement(preparedSelect);
      ps.setString(1, current);
      statement.close();
      result = ps.executeQuery();

      while (result.next()) {
      strt = result.getString("word");
      Large = result.getInt("Large");
      // some more code here

      keyWords.add(strt);
      }

      } catch (Exception e) {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
      }
      }