Jad J
Jad J

Reputation: 91

"unable to connect to database"

I'm trying to connection to my MySQL database and am getting an "unable to connect to database" exception. Can anyone spot what I'm doing wrong?

 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());
        }

    }

Upvotes: 1

Views: 1476

Answers (4)

COD3BOY
COD3BOY

Reputation: 12112

In first sight I see that you don't provide a username and password.

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

Upvotes: 3

phatfingers
phatfingers

Reputation: 10250

I notice you have a private method, "displaySqlErrors(...)". If you call that method from your catch block, like "displaySqlErrors(e)", then you will likely be able to determine the problem on your own.

Upvotes: 0

Hemant Metalia
Hemant Metalia

Reputation: 30688

Hi please check your classpath jars ? Does it have jar of mysql ?? It happens if the jar for mysql is not found in classpath because of it, it may not find com.mysql.jdbc.Driver class so throws an exception. Obvously after that you need to take the object of connection as specified by AVD and other people.

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94653

You have to set username and password.

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

Upvotes: 2

Related Questions