Reputation: 83
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...
Upvotes: 1
Views: 1804
Reputation: 308938
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;
}
}
Upvotes: 1