2010-10-30 2 views
1

Je tente d'obtenir une connexion à la base de données MySQL de mon université, mais la connexion est suspendue.Pourquoi java.sql.DriverManager.getConnection (...) est suspendu?

import java.sql.*; 

public class ConnectToDB { 
     public static void main(String args[]){ 
       try { 
         Class.forName("com.mysql.jdbc.Driver").newInstance(); 
         String url = "jdbc:mysql://db.cs.myUniversity.com/dbName"; 
         System.out.println("BEFORE"); 
         Connection con = DriverManager.getConnection(url,"me", "password"); 
         System.out.println("AFTER"); 
         ... 

Cet appel: time java ConnectToDB impression (après que je tue finalement il):

Copyright 2004, R.G.Baldwin 
BEFORE 
AFTER 

real 3m9.343s 
user 0m0.316s 
sys  0m0.027s 

Je viens de télécharger MySQL Connector/J de here. Je ne suis pas certain si cela fait partie du problème. J'ai suivi les directions assez précisément.

Je peux également vous connecter à mysql sur la ligne de commande comme ceci:

$ mysql -u me -h db.cs.myUniversity.com -p 
Enter password: 
Welcome to the MySQL monitor. Commands end with ; or \g. 
Your MySQL connection id is 882328 
Server version: 5.0.77 Source distribution 

Type 'help;' or '\h' for help. Type '\c' to clear the buffer. 

mysql> use dbName; 
Reading table information for completion of table and column names 
You can turn off this feature to get a quicker startup with -A 

Database changed 
mysql> SHOW tables; 
+-------------------+ 
| Tables_in_dbName | 
+-------------------+ 
| classics   | 
+-------------------+ 
1 row in set (0.00 sec) 

Problèmes possibles:

  • Le code Java j'ai écrit
  • Comment j'ai installé MySQL Connector/J
  • Une sorte de problème de réseau bloquant la connexion

Question: Que faire pour résoudre ce problème? Pourquoi l'appel getConnection est suspendu?

Je suivais this tutorial

+0

Je suis un idiot. Je vote pour fermer. – sixtyfootersdude

+0

Non, vous n'êtes pas. Vous avez posé une bonne question et fourni beaucoup de détails. Tu pensais tout le temps. Parfois, il suffit d'une autre paire d'yeux, surtout si vous observez le problème depuis longtemps. Ne sois pas si dur avec toi-même. J'ai vu de vrais eejits ici, et je ne vous comptais pas parmi eux. – duffymo

Répondre

5

La sortie que vous fournissez n'est pas utile.

Je vois AVANT et APRÈS avoir été imprimé, donc la connexion a été faite. Le code ne montre pas ce que ces horaires englobent, donc je ne peux pas dire ce qu'ils veulent dire. Si vous suggérez que votre code a dû être supprimé car la connexion n'a jamais été établie, c'est probablement parce que votre nom d'utilisateur, votre mot de passe et votre adresse IP client n'ont pas été autorisés.

Peut-être:

  1. votre réseau universitaire; Trouver un ingénieur réseau pour poser des questions sur les pare-feu.
  2. permission dans la base de données MySQL; trouver le DBA et demander.
  3. votre code; vous n'avez pas posté assez pour le dire. Poster toute la classe.

Quoi de neuf avec ce copyright? Je perdrais ça.

Ce code fonctionne. Modifiez-le pour que les paramètres pertinents correspondent à votre problème. (Mine utilise MySQL 5.1.51 et une table nommée Party.) Quand je l'exécute sur ma machine locale, j'obtiens un temps de mur de 641 ms.

package persistence; 

import java.sql.*; 
import java.util.*; 

/** 
* DatabaseUtils 
* User: Michael 
* Date: Aug 17, 2010 
* Time: 7:58:02 PM 
*/ 
public class DatabaseUtils 
{ 
/* 
    private static final String DEFAULT_DRIVER = "org.postgresql.Driver"; 
    private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party"; 
    private static final String DEFAULT_USERNAME = "pgsuper"; 
    private static final String DEFAULT_PASSWORD = "pgsuper"; 
*/ 
    private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver"; 
    private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party"; 
    private static final String DEFAULT_USERNAME = "party"; 
    private static final String DEFAULT_PASSWORD = "party"; 

    public static void main(String[] args) 
    { 
     long begTime = System.currentTimeMillis(); 

     String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER); 
     String url = ((args.length > 1) ? args[1] : DEFAULT_URL); 
     String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME); 
     String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD); 

     Connection connection = null; 

     try 
     { 
      connection = createConnection(driver, url, username, password); 
      DatabaseMetaData meta = connection.getMetaData(); 
      System.out.println(meta.getDatabaseProductName()); 
      System.out.println(meta.getDatabaseProductVersion()); 

      String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME"; 
      System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST)); 

      connection.setAutoCommit(false); 
      String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)"; 
      List parameters = Arrays.asList("Foo", "Bar"); 
      int numRowsUpdated = update(connection, sqlUpdate, parameters); 
      connection.commit(); 

      System.out.println("# rows inserted: " + numRowsUpdated); 
      System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST)); 
     } 
     catch (Exception e) 
     { 
      rollback(connection); 
      e.printStackTrace(); 
     } 
     finally 
     { 
      close(connection); 
      long endTime = System.currentTimeMillis(); 
      System.out.println("wall time: " + (endTime - begTime) + " ms"); 
     } 
    } 

    public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException 
    { 
     Class.forName(driver); 

     if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0)) 
     { 
      return DriverManager.getConnection(url); 
     } 
     else 
     { 
      return DriverManager.getConnection(url, username, password); 
     } 
    } 

    public static void close(Connection connection) 
    { 
     try 
     { 
      if (connection != null) 
      { 
       connection.close(); 
      } 
     } 
     catch (SQLException e) 
     { 
      e.printStackTrace(); 
     } 
    } 


    public static void close(Statement st) 
    { 
     try 
     { 
      if (st != null) 
      { 
       st.close(); 
      } 
     } 
     catch (SQLException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    public static void close(ResultSet rs) 
    { 
     try 
     { 
      if (rs != null) 
      { 
       rs.close(); 
      } 
     } 
     catch (SQLException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    public static void rollback(Connection connection) 
    { 
     try 
     { 
      if (connection != null) 
      { 
       connection.rollback(); 
      } 
     } 
     catch (SQLException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    public static List<Map<String, Object>> map(ResultSet rs) throws SQLException 
    { 
     List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); 

     try 
     { 
      if (rs != null) 
      { 
       ResultSetMetaData meta = rs.getMetaData(); 
       int numColumns = meta.getColumnCount(); 
       while (rs.next()) 
       { 
        Map<String, Object> row = new HashMap<String, Object>(); 
        for (int i = 1; i <= numColumns; ++i) 
        { 
         String name = meta.getColumnName(i); 
         Object value = rs.getObject(i); 
         row.put(name, value); 
        } 
        results.add(row); 
       } 
      } 
     } 
     finally 
     { 
      close(rs); 
     } 

     return results; 
    } 

    public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException 
    { 
     List<Map<String, Object>> results = null; 

     PreparedStatement ps = null; 
     ResultSet rs = null; 

     try 
     { 
      ps = connection.prepareStatement(sql); 

      int i = 0; 
      for (Object parameter : parameters) 
      { 
       ps.setObject(++i, parameter); 
      } 

      rs = ps.executeQuery(); 
      results = map(rs); 
     } 
     finally 
     { 
      close(rs); 
      close(ps); 
     } 

     return results; 
    } 

    public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException 
    { 
     int numRowsUpdated = 0; 

     PreparedStatement ps = null; 

     try 
     { 
      ps = connection.prepareStatement(sql); 

      int i = 0; 
      for (Object parameter : parameters) 
      { 
       ps.setObject(++i, parameter); 
      } 

      numRowsUpdated = ps.executeUpdate(); 
     } 
     finally 
     { 
      close(ps); 
     } 

     return numRowsUpdated; 
    } 
} 
+0

Ha! Wow, vous avez totalement raison! En fait, je n'ai pas fini par tuer ce processus (je les tuais habituellement après 1 minute).Celui-ci a fini correctement (et n'a pas pendu indéfiniment). Question stupide. Merci pour l'aide. – sixtyfootersdude

+0

Merci d'avoir accepté la réponse. Pourquoi ne pas voter aussi? – duffymo

Questions connexes