简体   繁体   English

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

[英]No suitable driver found (but the driver is there!)

well i'm suffering here to make my first web app in java using eclipse. 好吧,我在这里苦于用eclipse在Java中制作我的第一个Web应用程序。 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. 事实是,我拥有mysql驱动程序JDBC,并创建了与数据库建立连接的类,我编写了一本书以在数据库中注册一些联系人,例如个人组织者,它在Java中效果很好,没有错误。 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 . 但是在Java EE中,我无法将联系人保存在数据库中,因为出现了以下错误: 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 ! 好吧,它具有相同的类来进行连接,我已经将mysql JDBC驱动程序(例如build path-> add)构建到构建路径中,我不知道为什么它在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... 我是新来的,不知道我是否做对了,但是无论如何,对于冗长的代码感到抱歉...

You don't say how you're deploying this app. 您没有说如何部署此应用程序。 Let's assume that it's a properly constructed WAR file deployed to Tomcat. 假设它是部署到Tomcat的正确构造的WAR文件。

The Tomcat docs say JDBC drivers need to be added to the Tomcat /lib directory. Tomcat文档说JDBC驱动程序需要添加到Tomcat / lib目录。 Try putting it there and restarting Tomcat. 尝试将其放到那里,然后重新启动Tomcat。

Your ConnectionFactory is a bad idea. 您的ConnectionFactory是个坏主意。 The right thing to do is to set up a pooled JNDI data source in Tomcat. 正确的做法是在Tomcat中设置池化的JNDI数据源。 The docs show you how. 文档向您展示了如何。

Can you log into MySQL using the admin in the command shell? 您可以在命令外壳中使用admin登录MySQL吗?

What port is MySQL daemon listening on? MySQL守护程序在监听哪个端口? You didn't supply a port number, so it assumes 3306. 您没有提供端口号,因此假定为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. 现在将需要Eclipse,Tomcat,Web应用程序以及您不了解的所有其他功能。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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