0

This is the pure java code snippets. I'm trying to connecting jdbc to the project all the crud operation is excuting under the main method and their is error called classnotfound exception.

public class Appinitializer {
    public static void main(String[] args) {
        // save
        try {
            Customer customer = new Customer(1001, "chamithu", "Panadura", 25000, new Date());
            if (saveCustomer(customer)) {
                System.out.println("Success!");
            } else {
                System.out.println("Try Again!");
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        // save

    }

    private static boolean saveCustomer(Customer c) throws ClassNotFoundException, SQLException {
        String sql = "INSERT INTO customer VALUES (?,?,?,?,?)";
        PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
        preparedStatement.setLong(1, c.getId());
        preparedStatement.setString(2, c.getName());
        preparedStatement.setString(3, c.getAddress());
        preparedStatement.setDouble(4, c.getSalary());
        preparedStatement.setObject(5, c.getDOB());
        return preparedStatement.executeUpdate() > 0;
    }

    private static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernatedb", "root", "1234");
    }
}

This is the error occurred when I run the program.

enter image description here

  • you need to post the trace in its entirety – nbk Aug 22 '23 at 16:23
  • What do you have as the dependency for the driver in Maven/Gradle? – k314159 Aug 22 '23 at 16:29
  • 1
    [Please never post images of text](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors/285557#285557). They are not searchable, we cannot copy-paste... Always copy-paste the text and format it properly. – g00se Aug 22 '23 at 16:37
  • 2
    It looks like you don't have installed the driver JDBC – Pablo DbSys Aug 22 '23 at 17:00
  • Either the JAR for the JDBC driver class is not in the CLASSPATH or you have the wrong driver class name. – duffymo Aug 22 '23 at 17:05
  • 1
    A few things, but here are two: make sure you have the mysql connector-j driver in your classpath. Get rid of that `Class.forName` loading. It's no longer necessary. The first thing that will probably happen then is that the error will change. Please post it - as *text* (formatted as code) – g00se Aug 22 '23 at 20:24
  • Does this answer your question? [Connect Java to a MySQL database](https://stackoverflow.com/questions/2839321/connect-java-to-a-mysql-database) – Simulant Aug 24 '23 at 10:30

0 Answers0