简体   繁体   中英

SQLException when I run a Java web app

I'm starting with Java EE and set up a simple project in Eclipse for Java EE. The structure is a traditional Java Web project default: Tomcat integrated with Eclipse and some basic servlets.

In detail: I have this class to represent a contact: package br.myagenda.data;

import java.util.Calendar;

public class Contato {
    private long _id;
    private final String _nome;
    private final String _endereco;
    private final String _email;
    private final Calendar _dataNascimento;

    public Contato(String nome, String endereco, String email, Calendar dataNascimento)    
    {
        _nome = nome;
        _endereco = endereco;
        _email = email;
        _dataNascimento = dataNascimento;
    }

    public void setId(long id) {
        _id = id;
    }

    public long getId() {
        return _id;
    }

    public String getNome() {
        return _nome;
    }

    public String getEndereco() {
        return _endereco;
    }

    public String getEmail() {
        return _email;
    }

    public Calendar getDataNascimento() {
        return _dataNascimento;
    }

And this is part of another class to translate instances of the above class in SQL: import br.myagenda.data.Contato; import br.myagenda.util.SqlConnectionFactory;

public class ContatoDAO {
private final Connection _connection;

public ContatoDAO() {
    _connection = SqlConnectionFactory.getConnection();
}

public void add(Contato contato) {
    String sqlStatement = "INSERT INTO contatos (nome, email, endereco, data_nascimento)"
            + "VALUES (?,?,?,?)";

    PreparedStatement statemant = null;
    try {           
        statemant = _connection.prepareStatement(sqlStatement);         
        statemant.setString(1, contato.getNome());
        statemant.setString(2, contato.getEmail());
        statemant.setString(3, contato.getEndereco());

        Date dataParaGravar = new Date(Calendar.getInstance().getTimeInMillis());
        statemant.setDate(4, dataParaGravar);
        statemant.execute();
        statemant.close();          
    } catch(SQLException e) {
        throw new RuntimeException(e);
    }
}
...

And a class with the main method called "ContatoDaoTest" that calls the above class methods for obvious reasons.

The funny thing and the problem is: If i run the test class (run as a normal Java Application), the class access the database just fine.

However, I have HTML pages to show a page to fill a form and a Servlet to store the user input. Basically, it's a page to the page visitor register a contact, so, internally, the servlet will instance a Contato and a ContatoDAO to store in the database.

<!DOCTYPE html SYSTEM "html.dtd"><html>
<head>
    <title>MyAgenda --- Adicionar um contato</title>
</head>
    <body>
        <form action="addContact">
            Nome: <input type="text" name="nome"/><br />
            E-Mail: <input type="text" name="email"/><br />
            Endereço: <input type="text" name="address" /><br />
            Data Nascimento: <input type="text" name="dataNascimento" /><br />
            <input type="submit" value="Gravar" />
        </form>
    </body>
</html>

But, when I fire the "Gravar" button, Tomcat shows an error page saying there was a java.sql:SQLException: No suitable driver found!

The question is that: Why as a normal Java application, the database access works, but as a Java web app, it doesn't work?

Notes:

1 - The mysql-connector IS inside the WebContent/lib.

2 - The mysql-connector IS added to the eclipse build path.

3 - I CAN access the mysql-connector internal classes through "import".

Adding: Actually, I found a solution to this, but I feel this is not very convenient:

Ancient SqlConnectorFactory:

public class SqlConnectionFactory {
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost/my_agenda",    "root",     "senhadomysql");
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

New:

public class SqlConnectionFactory {
    public static Connection getConnection() {
        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //this line made the diference.
            return DriverManager.getConnection("jdbc:mysql://localhost/my_agenda",    "root",     "senhadomysql");
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Why as a normal Java application, the database access works, but as a Java web app, it doesn't work?

Tomcat can't find the driver com.mysql.jdbc.Driver. The jar with mysql-connector-java should be in (your_tomcat)/lib directory Tomcat

Your SqlConnectionFactory should look something like this

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

For more details you can look a link: http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM