Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

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

1 Answer

0 votes
by (46k points)

DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:

Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");

or instantiating and configuring one from your database driver directly:

MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");

and then obtain connections from it, same as above:

Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();

Related questions

0 votes
1 answer
asked Apr 6, 2021 in Java by dante07 (13.1k points)
0 votes
0 answers
asked Feb 17, 2021 in Java by Harsh (1.5k points)
0 votes
1 answer

Browse Categories

...