2011-12-05 58 views
1

我试图连接到我的MySQL数据库,并得到“无法连接到数据库”异常。任何人都可以发现我做错了什么吗?“无法连接到数据库”

public class SQL { 


     //database variables 
     private Connection connection; 

     public SQL() { 
      // DATABASE CONNECTION 
      try { 
       Class.forName("com.mysql.jdbc.Driver").newInstance(); 
      } catch (Exception e) { 
       System.err.println("Unable to find and load driver"); 
       System.exit(1); 
      } 

      try { 
       connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tools"); 
      } catch (SQLException e){ 
       System.out.println("Unable to connect to database"); 
       System.exit(1); 
      } 

     } 

     public void database() { 
      Vector<String> v = new Vector<String>(); 
      try { 
       Statement statement = connection.createStatement(); 
       ResultSet rs = statement 
         .executeQuery("SELECT nameofsong FROM lyrics_lyrics"); 

       while (rs.next()) { 
        v.addElement(rs.getString("nameofsong")); 
       } 
       rs.close(); 
      } catch (SQLException e) { } 
     } 


     private void displaySQLErrors(SQLException e){ 
      System.out.println("SQLException: " + e.getMessage()); 
      System.out.println("SQLState:  " + e.getSQLState()); 
      System.out.println("VendorError: " + e.getErrorCode()); 
     } 

    } 
+2

您可以使用e.printStackTrace()打印异常的堆栈跟踪吗?并发布输出。 – Andy

+1

请发布完整的stacktrace。 –

+0

你指定了用户名和密码吗? – Cyntech

回答

2

您必须设置用户名和密码。

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tools", 
              "username","password"); 
+0

啊,我知道我的mysql密码,但有什么办法知道用户名,我忘了它.. –

+0

@JJJ - 你可以重置根密码 - http://dev.mysql.com/doc/refman/ 5.0/en/resetting-permissions.html – adatapost

3

在第一眼我看你不提供usernamepassword

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tools",username,password); 
                       ^ ^
0

嗨请检查您的classpath jar吗?它有罐子的MySQL吗?如果因为它而在类路径中找不到mysql的jar,它可能找不到com.mysql.jdbc.Driver类,所以会引发异常。在此之后,你需要按照AVD和其他人的规定来接通连接对象。

+0

对,jay是在类路径中,它都很好,每个人的权利,我只需要指定我的用户名和密码,问题是我不知道用户名...任何方式抬头? –

+0

检查根目录为用户名 –

0

在您的情况下,您必须添加用户名nad密码。

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tools","user","password"); 

堂妹

Parameters: 
url - a database url of the form jdbc:subprotocol:subname ex: "jdbc:mysql://localhost:3306/tools" 
user - the database user on whose behalf the connection is being made 
password - the user's password 
0

我注意到你有一个私有方法, “displaySqlErrors(......)”。如果您从catch块中调用该方法,如“displaySqlErrors(e)”,那么您可能会自行确定问题。

+0

我使用'root'作为用户名,并通过我的密码,它的工作!谢谢大家 –