2017-10-04 2 views
0
String url = "jdbc:mysql://localhost:3306/mysql"; 
String user = "root"; 
String pass = "root1"; 

try { 
    Class.forName("com.mysql.jdbc.Driver"); 
    Connection connection = DriverManager.getConnection(url, user, pass); 
    System.out.println("Connected to database"); 
} catch (Exception e) {   
    System.out.println(e); 
    System.out.println("Could not connect to database"); 
} 

Le mot de passe doit être "root". Le programme n'affiche pas le message dans le bloc catch et cesse de fonctionner. Quelqu'un peut-il me dire ce qui se passe? Je m'excuse J'ai posé une mauvaise question. Le problème est déjà résolu, merci. Cela permet de vérifier correctement si la connexion existe.La connexion MySQL JDBC cesse de fonctionner

if (conn1 != null) { 
    System.out.println("Connected to the database test1"); 
} 
+0

d'essayer d'imprimer stackTrace dans le bloc catch comme 'e.printStackTrace()', également coller cette erreur ici . – Nidhi257

+0

Il ne montre rien dans la console, il suffit d'arrêter là. Il ne pénètre pas dans le bloc catch. –

+0

essayez de commenter cette ligne 'Class.forName (" com.mysql.jdbc.Driver ");' et re run. laissez voir ... – Nidhi257

Répondre

-1

Il existe trois façons différentes de se connecter à la base de données SQL comme indiqué dans le code ci-dessous

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException; 
import java.util.Properties; 

public class MySQLConnectExample { 
    public static void main(String[] args) { 

     // creates three different Connection objects 
     Connection conn1 = null; 
     Connection conn2 = null; 
     Connection conn3 = null; 

     try { 
      // connect way #1 
      String url1 = "jdbc:mysql://localhost:3306/test1"; 
      String user = "root"; 
      String password = "secret"; 

      conn1 = DriverManager.getConnection(url1, user, password); 
      if (conn1 != null) { 
       System.out.println("Connected to the database test1"); 
      } 

      // connect way #2 
      String url2 = "jdbc:mysql://localhost:3306/test2?user=root&password=secret"; 
      conn2 = DriverManager.getConnection(url2); 
      if (conn2 != null) { 
       System.out.println("Connected to the database test2"); 
      } 

      // connect way #3 
      String url3 = "jdbc:mysql://localhost:3306/test3"; 
      Properties info = new Properties(); 
      info.put("user", "root"); 
      info.put("password", "secret"); 

      conn3 = DriverManager.getConnection(url3, info); 
      if (conn3 != null) { 
       System.out.println("Connected to the database test3"); 
      } 
     } catch (SQLException ex) { 
      System.out.println("An error occurred. Maybe user/password is invalid"); 
      ex.printStackTrace(); 
     } 
    } 
} 
+0

merci pour votre aide. –

+0

Comment cela répond-il à la question? –

+0

Le vérifier si la connexion existe aide. if (conn1! = null) {System.out.println ("Connecté à la base de données test1"); } –