1

well i'm suffering here to make my first web app in java using eclipse. The thing is that i have the mysql driver JDBC and i made the class to make the connection with the database, i've made a book to register some contacts in the database, like a personal organizer, it worked out great in Java, no mistakes. But in java EE, i can't save contacts in the database because i got the error:java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/bDados. Well it have the same class to make the connection, i have put the mysql JDBC driver like build path->add to build path, and i don't know why it isn't working in Java EE ! here:

package br.com.caelum.servlet;

import java.sql.*;

public class ConnectionFactory {
    public Connection getConnection(){
        try{
            return DriverManager.getConnection(
                    "jdbc:mysql://localhost/bDados", "gabrielDados","25120107");
        }catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
}

import java.util.Calendar;

public class Contato {
   private Long id;
   private String nome;
   private String email;
   private String endereco;
   private Calendar dataNascimento;
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getNome() {
    return nome;
}
public void setNome(String nome) {
    this.nome = nome;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getEndereco() {
    return endereco;
}
public void setEndereco(String endereco) {
    this.endereco = endereco;
}
public Calendar getDataNascimento() {
    return dataNascimento;
}
public void setDataNascimento(Calendar dataNascimento) {
    this.dataNascimento = dataNascimento;
}
 }

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ContatoDao {
    private Connection connection;

    public ContatoDao(){
        this.connection = new ConnectionFactory().getConnection();
    }
    public void adiciona(Contato contato) {
         String sql = "insert into contatos " +
                 "(nome,email,endereco,dataNascimento)" +
                 " values (?,?,?,?)";

         try {
             // prepared statement para inserção
             PreparedStatement stmt = connection.prepareStatement(sql);

             // seta os valores
             stmt.setString(1,contato.getNome());
             stmt.setString(2,contato.getEmail());
             stmt.setString(3,contato.getEndereco());
             stmt.setDate(4, new Date(
                     contato.getDataNascimento().getTimeInMillis()));

             // executa
             stmt.execute();
             stmt.close();
         } catch (SQLException e) {
             throw new RuntimeException(e);
         }
     }
}
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/adicionaContato")
public class AdicionaContatoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request,
                        HttpServletResponse response)
                        throws IOException, ServletException {
        // busca o writer
        PrintWriter out = response.getWriter();

        // buscando os parâmetros no request
        String nome = request.getParameter("nome");
        String endereco = request.getParameter("endereco");
        String email = request.getParameter("email");
        String dataEmTexto = request
                .getParameter("dataNascimento");
        Calendar dataNascimento = null;

        // fazendo a conversão da data
        try {
            Date date = 
                    new SimpleDateFormat("dd/MM/yyyy")
                    .parse(dataEmTexto);
            dataNascimento = Calendar.getInstance();
            dataNascimento.setTime(date);
        } catch (ParseException e) {
            out.println("Erro de conversão da data");
            return; //para a execução do método
        }

        // monta um objeto contato
        Contato contato = new Contato();
        contato.setNome(nome);
        contato.setEndereco(endereco);
        contato.setEmail(email);
        contato.setDataNascimento(dataNascimento);

        // salva o contato
        ContatoDao dao = new ContatoDao();
        dao.adiciona(contato);

        // imprime o nome do contato que foi adicionado
        out.println("<html>");
        out.println("<body>");
        out.println("Contato " + contato.getNome() +
                " adicionado com sucesso");
        out.println("</body>");
        out.println("</html>");
    }
}

<html>
    <body>
        <h1>Adiciona Contatos</h1>
        <br/>
        <form action="adicionaContato">
            Nome: <input type="text" name="nome" /><br />
            E-mail: <input type="text" name="email" /><br />
            Endereço: <input type="text" name="endereco" /><br />
            Data Nascimento: <input type="text" name="dataNascimento" /><br />
            <input type="submit" value="Gravar" />
        </form>
    </body>
</html>

I'm new here, don't know if i did it right but, anyway, sorry for the long code...

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gabriel Ozzy
  • 73
  • 1
  • 7
  • Are you sure it's not a 32 vs 64 bit mixup? If Java and Java EE have different bitness, they may not be able to share the driver. – Joachim Isaksson Jul 25 '14 at 23:11
  • 1
    The MySQL Connector-J is a type IV driver - pure Java. – duffymo Jul 25 '14 at 23:14
  • Well i use Linux, and in te mysql website there's only one JDBC to download... – Gabriel Ozzy Jul 25 '14 at 23:14
  • possible duplicate of [No suitable driver found for 'jdbc:mysql://localhost:3306/mysql](http://stackoverflow.com/questions/8146793/no-suitable-driver-found-for-jdbcmysql-localhost3306-mysql) – Gas Jul 25 '14 at 23:23
  • @Gas, sorry but i read it before and didn't worked out for me, that's why i asked again... – Gabriel Ozzy Jul 25 '14 at 23:26
  • Why not for you? Because you did it wrong....it works if you know what you're doing. – duffymo Jul 25 '14 at 23:59
  • Yeah, i really don't know, that's why i said i'm learning... Geez, this is my first Web Application, understand it... Just wanted to get more friendly people to help me out. – Gabriel Ozzy Jul 26 '14 at 00:04
  • Ok, maybe I overreacted. Comment removed. – Gas Jul 26 '14 at 00:16
  • @Gas maybe i did it too, comment removed, hope we can get along and help each other out in the future. – Gabriel Ozzy Jul 26 '14 at 00:22
  • Ok, describe how you deploy your app to Tomcat, and what filename you are using as driver. You may need to add port in your JDBC url. – Gas Jul 26 '14 at 00:29
  • Well, i just added the folder to the tomcat8 server, everything i did went out ok (simple stuffs), it's just when i tap the "gravar" button that i get this error... Basically, everything is ok, until i make the request to save the information in the database. I'm following some online-lessons and followed step by step perfectly, i could put the link here but it's portuguese... How i do to add port in my JDBC url ? – Gabriel Ozzy Jul 26 '14 at 00:45
  • Oh, and the driver name is the mysql-connector-java-5.1.31.bin.jar... – Gabriel Ozzy Jul 26 '14 at 00:53
  • 1
    @Gas, problem resolved, will be updating the solution here tomorrow, thx for all – Gabriel Ozzy Jul 26 '14 at 01:21
  • I've rollback your replacement of the question by a solution. Please find [your solution in the revision history](https://stackoverflow.com/revisions/63032ae3-d92c-4630-ae0d-dd01e51b471a/view-source) and post it as an answer of its own. – Cœur May 19 '18 at 13:47

1 Answers1

1

You don't say how you're deploying this app. Let's assume that it's a properly constructed WAR file deployed to Tomcat.

The Tomcat docs say JDBC drivers need to be added to the Tomcat /lib directory. Try putting it there and restarting Tomcat.

Your ConnectionFactory is a bad idea. The right thing to do is to set up a pooled JNDI data source in Tomcat. The docs show you how.

Can you log into MySQL using the admin in the command shell?

What port is MySQL daemon listening on? You didn't supply a port number, so it assumes 3306.

Is the database listener running on your local machine?

Try running this stand alone program on a command line to test out your database connection. Modify the connection string and credentials for your case, compile and run it. The class I'm giving you works, without question. It'll take Eclipse, Tomcat, web apps, and all the other things that you don't know out of the equation for now. See if you can connect; get that right, then move on to the next level.

package persistence;

import java.sql.*;
import java.util.*;

/**
 * util.DatabaseUtils
 * User: Michael
 * Date: Aug 17, 2010
 * Time: 7:58:02 PM
 */
public class DatabaseUtils {
/*
    private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DEFAULT_URL = "jdbc:oracle:thin:@host:1521:database";
    private static final String DEFAULT_USERNAME = "username";
    private static final String DEFAULT_PASSWORD = "password";
*/
/*
    private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
    private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
    private static final String DEFAULT_USERNAME = "pgsuper";
    private static final String DEFAULT_PASSWORD = "pgsuper";
*/
    private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
    private static final String DEFAULT_USERNAME = "party";
    private static final String DEFAULT_PASSWORD = "party";

    public static void main(String[] args) {
        long begTime = System.currentTimeMillis();

        String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
        String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
        String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
        String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);

        Connection connection = null;

        try {
            connection = createConnection(driver, url, username, password);
            DatabaseMetaData meta = connection.getMetaData();
            System.out.println(meta.getDatabaseProductName());
            System.out.println(meta.getDatabaseProductVersion());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(connection);
            long endTime = System.currentTimeMillis();
            System.out.println("wall time: " + (endTime - begTime) + " ms");
        }
    }

    public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0)) {
            return DriverManager.getConnection(url);
        } else {
            return DriverManager.getConnection(url, username, password);
        }
    }

    public static void close(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void close(Statement st) {
        try {
            if (st != null) {
                st.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection connection) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static List<Map<String, Object>> map(ResultSet rs) throws SQLException {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        try {
            if (rs != null) {
                ResultSetMetaData meta = rs.getMetaData();
                int numColumns = meta.getColumnCount();
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<String, Object>();
                    for (int i = 1; i <= numColumns; ++i) {
                        String name = meta.getColumnName(i);
                        Object value = rs.getObject(i);
                        row.put(name, value);
                    }
                    results.add(row);
                }
            }
        } finally {
            close(rs);
        }
        return results;
    }

    public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException {
        List<Map<String, Object>> results = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters) {
                ps.setObject(++i, parameter);
            }
            rs = ps.executeQuery();
            results = map(rs);
        } finally {
            close(rs);
            close(ps);
        }
        return results;
    }

    public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException {
        int numRowsUpdated = 0;
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters) {
                ps.setObject(++i, parameter);
            }
            numRowsUpdated = ps.executeUpdate();
        } finally {
            close(ps);
        }
        return numRowsUpdated;
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561