找不到合适的驱动程序(但驱动程序在那里!)

时间:2014-07-25 23:09:18

标签: java mysql eclipse java-ee jdbc

我正在努力使用eclipse在java中创建我的第一个Web应用程序。问题是我有mysql驱动程序JDBC,我让类与数据库建立连接,我已经写了一本书来注册数据库中的一些联系人,就像个人组织者一样,它在Java中表现很好,没有错误。但是在java EE中,我无法在数据库中保存联系人,因为我收到错误:java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/bDados。好吧它有相同的类来建立连接,我已经把mysql JDBC驱动程序像build path->添加到构建路径,我不知道为什么它不能在Java EE中工作!这里:

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>

我是新来的,不知道我做得对,但无论如何,抱歉长代码......

1 个答案:

答案 0 :(得分:1)

您不会说您如何部署此应用。让我们假设它是一个部署到Tomcat的正确构造的WAR文件。

Tomcat文档说需要将JDBC驱动程序添加到Tomcat / lib目录中。尝试将其放在那里并重新启动Tomcat。

你的ConnectionFactory是个坏主意。正确的做法是在Tomcat中设置池化的JNDI数据源。 docs告诉你如何。

您可以使用命令shell中的admin登录MySQL吗?

MySQL守护进程正在侦听哪个端口?您没有提供端口号,因此它假定为3306。

数据库侦听器是否在本地计算机上运行?

尝试在命令行上运行此独立程序以测试数据库连接。修改案例的连接字符串和凭据,编译并运行它。我给你的课程毫无疑问。它现在将Eclipse,Tomcat,Web应用程序以及您不了解的所有其他内容排除在外。看看你是否可以连接;做到这一点,然后进入下一个级别。

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;
    }
}