Problem calling Drivemanager.getConnection?

Asked

Viewed 208 times

3

I am studying Java with database and I am doing some examples. On the PC with Windows I used a code and it worked, no problem occurred, now I returned to use Linux and the same code is giving error when calling the method DriveManager.getConnection of JDBC.

Follow the code below.

package br.com.utd.jdbc;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import com.mysql.jdbc.Connection;

public class Conexao {
    private final static String URL = "jdbc:mysql://127.0.0.1:3306/livraria";
    private final static String USUARIO = "root";
    private final static String SENHA = "**********";

    public static Connection factoryConexao(){
        Connection conexao = null;
        try{
            conexao = DriverManager.getConnection(URL, USUARIO, SENHA);
            return conexao;
        }catch(SQLException e1){
            JOptionPane.showMessageDialog(null,  
                       "Falha na conexão com o banco de dados:"+e1);
            return conexao;
        }
    }

}

The error is the following Eclipse suggests adding a cast with Connection in:

conexao = DriverManager.getConnection(URL, USUARIO, SENHA);

I can’t understand, why make a cast with Connection if he’s a Connection?

inserir a descrição da imagem aqui

  • Add the error if possible to the question. If it is not a stacktrace, add an image showing the eclipse message.

1 answer

2


I can’t understand, why cast with Connection if he’s a Connection?

It happens because it has import wrong (import com.mysql.jdbc.Connection;) in your code the correct would be imports java.sql.Connection;, the others are correct.

The error in the picture is saying different types, and the Eclipse is trying to fix your code by giving a cast, but, the problem really was that the imports is wrong for Connection.

The imports correct are:

import java.sql.Connection; 
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane; // esse é o único que não faz parte do problema

Reference:

  • 1

    It worked, thank you.

  • Only one fix, only import import com.mysql.jdbc.Connection; is incorrect, the others are right.

  • @diegofm I put for them all imports as they should be, I understand that only this is wrong (import com.mysql.jdbc.Connection;), but also missing another import (java.sql.Connection;) For the code to work, I wanted to summarize the problem as a whole and show the user which are the correct imports, I will ratify this in the answer, but, I will also have to position what is missing. Thank you.

  • @diegofm ready

Browser other questions tagged

You are not signed in. Login or sign up in order to post.