[resolvido] Erro ao conectar com my sql

5 respostas
Vinifilpo

Criei uma servlet pra testar conexão com um banco mysql, não consigo efetuar a conexão.Coloquei os arquivos do driver mysql na pasta lib e depois importei a o .jar. também tentei acessar com localhost:3306 e localhost:8080.Quando executo a servlet ele não apresenta mensagem de “conexão efetuada com sucesso” , nem “Problemas ao tentar conectar com o banco de dados”, essa ultima soh aeh apresentada quando removo a linha de registro do driver.
Segue o codigo:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class testeBD
 */
public class testeBD extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public testeBD() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @throws IOException 
	 * @see Servlet#init(ServletConfig)
	 */
	
		
		 public void init(ServletConfig conf) throws ServletException {
             
             super.init(conf);

              Connection con;
			try {
                           Class.forName("com.mysql.jdbc.Driver");
                           con = DriverManager.getConnection("jdbc:mysql://http://localhost/agenda", "root", "");
                           System.out.print("conexão efetuada com sucesso!");
              } catch (Exception e) {
                           System.out.println("Problemas ao tentar conectar com o banco de dados");
                           con = null;
              }
   }
	

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response, ServletConfig conf) throws ServletException, IOException {
		// TODO Auto-generated method stub
		init(conf);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

5 Respostas

jpjcjbr

Tenta arrumar alguma maneira para ter certeza que o servlet ta respondendo, da uns System.out.println no comeco de cada método para ter certeza que o servlet ta registrado corretamente

ahh… passa o web.xml também, só pra ajudar a descobrir o que é

flws

GLEMES

Olá Vinifilpo,
Tenho uma dica pra vc, faça um JSF.

<html>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8”>
<title>JSP Page</title>
</head>
<body>

&lt;%
    java.sql.Connection connection = null;
try {
    // Load the JDBC driver
    String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
    Class.forName(driverName);

    // Create a connection to the database
    String serverName = "localhost";
    String mydatabase = "SEU BANCO";
    String url = "jdbc:mysql://" + serverName +  "/" + mydatabase; // a JDBC url
    String username = "SEU ESUARIO";
    String password = "SUA SENHA";
    connection = java.sql.DriverManager.getConnection(url, username, password);
    out.println("Conexão feita com sucesso!");
    
} catch (ClassNotFoundException e) {
    out.println("Não foi possível encontrar o driver: "+e.toString());
} catch (java.sql.SQLException e) {
    out.println("Não foi possível conectar ao banco de dados: "+e.toString());
}
    %&gt;

&lt;/body&gt;

</html>

Vinifilpo

A servlet tá respondendo.O System.out.print() não exibe mensagem quando está dentro do try ou do catch, qando está fora ele mostra a mensagem

Esse é o web.xml:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;display-name&gt;Con_BD&lt;/display-name&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;default.html&lt;/welcome-file&gt; &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;servlet&gt; &lt;description&gt;&lt;/description&gt; &lt;display-name&gt;testeBD&lt;/display-name&gt; &lt;servlet-name&gt;testeBD&lt;/servlet-name&gt; &lt;servlet-class&gt;testeBD&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;testeBD&lt;/servlet-name&gt; &lt;url-pattern&gt;/testeBD&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt;

dcorteztec

testar com esa classe aki pra ve se ta tudo OK

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connectar {
public static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver")//O driver de conexão;
return DriverManager.getConnection(
"jdbc:mysql://localhost/banco que voce criou ", "usuario do banco", "ea senha do banco");//Url de conexão
} catch (ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
}
3 ° A classe de teste

import java.sql.Connection;
import java.sql.SQLException;
public class TestConecta {
public static void main(String[] args) throws SQLException {
Connection con = Connectar.getConnection() //aqui você esta instaciando a classe de conexão;
con.close() // fechar a conexão;
System.out.println("SUCESSO") // mensagem de sucesso que devera aparecer no seu consele;
}
}
Vinifilpo

Agora funcionou perfeitamente. :smiley:
Obrigado!

Criado 30 de outubro de 2010
Ultima resposta 1 de nov. de 2010
Respostas 5
Participantes 4