“无法连接到数据库”

时间:2011-12-05 05:18:22

标签: java mysql

尝试连接到我的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());
        }

    }

5 个答案:

答案 0 :(得分:3)

乍一看,我发现您没有提供usernamepassword

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

您好,请检查您的classpath罐子?它有jar的mysql吗?如果在类路径中找不到mysql的jar,就会发生这种情况,它可能找不到com.mysql.jdbc.Driver类,因此抛出异常。在此之后,您需要获取AVD和其他人指定的连接对象。

答案 3 :(得分:0)

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

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

COS

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

答案 4 :(得分:0)

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