How do you connect to a MySQL database in Java?
When I try, I get
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Or
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
DataSourceDriverManageris a fairly old way of doing things. The better way is to get aDataSourceobject. Either by using JNDI to look one up that your app server container already configured for you:… or by instantiating and configuring one from your database driver directly, such as
com.mysql.cj.jdbc.MysqlDataSource(see documentation):… and then obtain connections from it, same as above:
In modern Java, use try-with-resources syntax to automatically close JDBC resources (now
AutoCloseable).