Dragos
Dragos

Reputation: 296

Connecting to a MySQL DataBase with JDBC

I have a simple code that needs to connect to a mysql DB and execute a query.

try {
            conn =
               DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=1234");

                Statement stm = conn.createStatement();
                stm.executeQuery(query);
                return true;

This code works like a charm in a test project with only a class with void main. But in my project that is a web application, I'm using apache tomcat and the same code displays the error:

SQLException: No suitable driver found for jdbc:mysql://localhost/test?user=root&password=1234

I've added the jar, the classpath the everything. Is there something special that I need to do because I'm using tomcat? Thanks, Dragos

Upvotes: 0

Views: 1026

Answers (3)

Dragos
Dragos

Reputation: 296

I have found the problem. I had to add the jdbc in the deployment assembly above the java build path in the configure build path window.

Upvotes: 1

SMA
SMA

Reputation: 37023

You forgot to load driver

 Class.forName("com.mysql.jdbc.Driver");

Before getting connection. Also you are missing port from your url.

Also you should be using

getConnection(String url, String user, String password) 

API for better readability rather than providing user/pass in url.

Upvotes: 0

Mise
Mise

Reputation: 3557

Use:

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=1234");

Upvotes: 1

Related Questions