How to recognize MySQL instances using Java and allow the user to choose the database?

3

I'm developing a project that is required to be able to access different banks from MySQL that are allocated on machines as well as on servers.

In order to allow the selection of a bank by the user that will execute the routines in this selected bank. If anyone knows how it is done to get the list of banks and tables from these on the machine and how this process is done on an external server link.

I think I'll have to get all the schema of banks , but I'm not sure what file and how I'll do it for the server. For all intents and purposes I am developing Java this project.

    
asked by anonymous 11.04.2014 / 21:05

1 answer

3

Code responsible for bringing a list of Bancos de Dados of a MYSQL Server and immediately after choosing a Banco show its Tabelas .

package javaapplication1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JavaApplication1 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {        
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("---------------------------------------------------------------");
        try (Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost/","root","senha")) {                        
            ResultSet result = conexao.createStatement().executeQuery("show databases;");
            System.out.println("Bancos de Dados");
            while (result.next()){
                System.out.println(result.getString(1));
            }            
            conexao.close();            
        }
        System.out.println("");        
        System.out.println("---------------------------------------------------------------");
        try (Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost/generics","root","senha")) {                        
            ResultSet result = conexao.createStatement().executeQuery("show tables;");
            System.out.println("Tabelas de Banco de Dado Selecionado (Banco: generics)");
            while (result.next()){
                System.out.println(result.getString(1));
            }            
            conexao.close();            
        }        
    }
}

Note that the first getConnection I do not pass the Banco name so that I can bring up the list of all Bancos on that Server ( show databases command):

DriverManager.getConnection("jdbc:mysql://localhost/","root","senha")

In the next getConnection I pass Banco generics and it will bring me the tables contained in this Banco (command show tables ):

DriverManager.getConnection("jdbc:mysql://localhost/generics","root","senha")

Result obtained:

In this case it was for a localhost bank, but if you put ip externo of Servidor MYSQL it also has the same result ...

    
12.04.2014 / 00:04