0

I am trying to follow a tutorial in a book on connecting a program to a database with JDBC. I am confused on what the first block of code is doing in the class. whan i run the code i get an error saying that java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/book_store

and the code is throwing an exception in that first block inside the class. do i need to add some sort of dependency or library to the project?

as you can tell this is my first attempt at using a db...

package com.apress.books.dao;

import com.apress.books.model.Author;
import com.apress.books.model.Book;
import com.apress.books.model.Category;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BookDAOImpl implements BookDAO {

static {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
    }
}

private Connection getConnection() throws SQLException {
    return DriverManager.getConnection("jdbc:mysql://localhost:8889/book_store",
            "root", "password");
}

private void closeConnection(Connection connection) {
    if (connection == null)
        return; try {
        connection.close();
    } catch (SQLException ex) {
    }
}
@Override
public void insert(Book book) {

}

@Override
public void update(Book book) {

}

@Override
public void delete(Long bookId) {

}
}
StillLearningToCode
  • 2,271
  • 4
  • 27
  • 46

1 Answers1

2

In essence this is a ClassNotFoundException. Your first catch clause is empty and thus, although the exception is being caught, you are not acting upon it. In the least, I would do something like this:

static {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        throw ex;
    }
}

This would help you to see better what is causing your troubles.

Moving on to a solution:

If you are using Maven, you need to add the following dependency in your pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.35</version>
</dependency>

And if you want, change the version to any one found here.

Otherwise, you need to download the jar from the same link and include it in your project dependencies.

Luke Bajada
  • 1,737
  • 14
  • 17