Find the jdbc mysql driver and establish connection

2

I'm trying to make a connection to java directly with jdbc. I inserted in the project the jdbc mysql jar in the project properties, javabuildpath and adding the external jar. I am taking the following example and it seems to me that you can not find the bank.

import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.SQLException;  

public class Disciplina {  

private int idDisciplina;  
private String disciplina;  
private float cargaHoraria;  

public static void main(String args[]) throws SQLException {  
Connection conexao = DriverManager  
.getConnection("jdbc:mysql://localhost/ucsal");  
System.out.println("Conectado!");  
conexao.close();  
}  
}  

Note: I throw an exception, I did not try because I want to see the error. And on the inserted jar, when I go in javabuildpatch, in the tab library, mysql jdbc has nothing inside the library. Everything is none (source target "none", java doc location "none", native library location "none").

I just downloaded the jar, did not download the rest of the contents of the mysql_jdbc.zip folder.

    
asked by anonymous 22.09.2016 / 20:11

2 answers

-1

I made the connection class as follows:

package conect_DB;  

import java.sql.DriverManager;  
import java.sql.SQLException;  

public class Conexao {  

    public static java.sql.Connection conexao;    
    private static String servidor = "jdbc:mysql://localhost:3306/ucsal";    

    public static boolean conectar() {    
    try {    

        Class driverMysql = Class.forName("com.mysql.jdbc.Driver");    

        conexao = DriverManager.getConnection(servidor, "root", "");    

        if (conexao == null) {    

        return false;  
        }  
    }  

    catch (ClassNotFoundException e) {    
        System.out.println(e.getMessage() + " on method 'conectar' error");    
    }    

    catch (SQLException e) {    
        System.out.println(e.getMessage());    
    }    

    return true;    
    }    

    public static void desconectar() {    
    try {    
        conexao.close();    
    }    

    catch (SQLException e) {    
        System.out.println(e.getMessage());    
    }    

    catch (NullPointerException e) {    
        System.out.println("method 'close()' error. Not conection opened");    
    }    
    }    

} 
    
27.09.2016 / 20:44
2

1st - Check on your database server , if you actually created the database ucsal ;

2nd -

DriverManager.getConnection("jdbc:mysql://localhost/ucsal", "seuLogin", "suaSenha");

3rd - I believe you did not add the driver incorrectly. One way to do this is:

  • Creating a folder in your project, titled lib ;
  • copy and paste it from your connectorJ into this directory;
  • Then add it to your classPath , if you are using Eclipse , right-click the Driver > build Path > Add to Build Path .
  • 22.09.2016 / 21:25