Skip to main content
Effectively managing your database connections ensures smooth workflow and access to the right data at the right time.

Active Connection Display

The current connection status is displayed in the SQL Editor’s connection panel:
// SqlEditorView.java - Line 291
public void setBaseDeDatos(String nombreBD) {
    if (nombreBD == null || nombreBD.isEmpty()) {
        txtBaseDeDatos.setText("Estado: No conectado");
        txtBaseDeDatos.setToolTipText("No hay conexión activa");
    } else {
        txtBaseDeDatos.setText("Conectado a: " + nombreBD);
        txtBaseDeDatos.setToolTipText("Conexión activa a: " + nombreBD);
    }
}

Connected State

Shows “Conectado a: [database_name]” when actively connected to a database.

Disconnected State

Shows “Estado: No conectado” when no active connection exists.

Connection Status Field

The connection status is displayed in a non-editable text field:
// SqlEditorView.java - Line 87
txtBaseDeDatos = new JTextField();
txtBaseDeDatos.setEditable(false);
txtBaseDeDatos.setFont(FUENTE_NORMAL);
txtBaseDeDatos.setBackground(new Color(230, 240, 255));
The status field uses a light blue background (#E6F0FF) to distinguish it from editable components and provides tooltip information on hover.

Switching Databases

To change to a different database, use the Cambiar BD (Change Database) button:

Confirmation Dialog

// Controller.java - Line 66
editorView.getBtnCambiarBD().addActionListener(e -> {
    int confirm = JOptionPane.showConfirmDialog(editorView,
        "¿Desea desconectarse y cambiar de base de datos?",
        "Confirmar",
        JOptionPane.YES_NO_OPTION);

    if (confirm == JOptionPane.YES_OPTION) {
        desconectar();
    }
});
1

Click Cambiar BD Button

Click the Cambiar BD button in the SQL Editor interface. This button is located in the right panel near the connection status.
// SqlEditorView.java - Line 106
btnCambiarBD = new JButton("Cambiar BD");
estilizarBoton(btnCambiarBD, false);
2

Confirm Disconnection

A confirmation dialog appears asking: “¿Desea desconectarse y cambiar de base de datos?” (Do you want to disconnect and change database?)Choose:
  • Yes: Proceed with disconnection
  • No: Cancel and maintain current connection
3

Return to Login

If confirmed, the application disconnects and returns you to the login screen:
// Controller.java - Line 217
private void desconectar() {
    try {
        modelo.desconectar();
        editorView.setBaseDeDatos(null);
        editorView.setVisible(false);
        loginView.setVisible(true);
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(editorView,
            "Error al desconectar: " + ex.getMessage(),
            "Error", JOptionPane.ERROR_MESSAGE);
    }
}
4

Connect to New Database

From the login screen, select a different database and click Conectar to establish a new connection.
Switching databases disconnects your current session. Any unsaved queries in the editor will be lost. Copy important queries before switching.

Disconnecting from Database

The disconnection process closes the MySQL connection properly:
// Model.java - Line 66
public void desconectar() throws SQLException {
    if (conexion != null && !conexion.isClosed()) {
        conexion.close();
    }
}

What Happens During Disconnection

The JDBC connection is properly closed:
conexion.close();
This releases database resources and terminates the session.
The editor view is reset to disconnected state:
editorView.setBaseDeDatos(null); // Shows "Estado: No conectado"
The SQL Editor closes and login view reopens:
editorView.setVisible(false);
loginView.setVisible(true);

Error Handling

// Controller.java - Line 224
catch (SQLException ex) {
    JOptionPane.showMessageDialog(editorView,
        "Error al desconectar: " + ex.getMessage(),
        "Error", JOptionPane.ERROR_MESSAGE);
}
If disconnection fails, an error dialog displays the specific SQL error message. This is rare but can occur if the connection is already closed or network issues exist.

Refreshing Table Listings

The Refrescar tablas (Refresh Tables) button updates the list of available tables:
// Controller.java - Line 64
editorView.getBtnRefrescarTablas().addActionListener(e -> refrescarTablas());

Refresh Process

1

Click Refresh Button

Click the Refrescar tablas button to initiate the refresh:
// SqlEditorView.java - Line 126
btnRefrescarTablas = new JButton("Refrescar tablas");
estilizarBoton(btnRefrescarTablas, false);
2

Fetch Tables from Database

The application queries the database metadata asynchronously:
// Controller.java - Line 192
private void refrescarTablas() {
    SwingWorker<List<String>, Void> worker = new SwingWorker<>() {
        @Override
        protected List<String> doInBackground() throws Exception {
            return modelo.obtenerTablasDeBaseDatos();
        }
    };
    worker.execute();
}
3

Update Table List

The table browser updates with the fresh list:
// Controller.java - Line 201
List<String> tablas = get();
editorView.actualizarListaTablas(tablas);

When to Refresh Tables

After Creating Tables

Refresh to see newly created tables in the browser:
CREATE TABLE new_table (id INT PRIMARY KEY);
Then click Refrescar tablas.

After Dropping Tables

Refresh to remove deleted tables from the list:
DROP TABLE old_table;
Then click Refrescar tablas.

External Changes

If another application or user modifies the database schema, refresh to see the changes.

Verify Structure

Periodically refresh to ensure your view matches the actual database structure.

Fetching Table Metadata

The obtenerTablasDeBaseDatos() method retrieves the current table list:
// Model.java - Line 78
public List<String> obtenerTablasDeBaseDatos() throws SQLException {
    List<String> tablas = new ArrayList<>();
    if (conexion != null && !conexion.isClosed()) {
        DatabaseMetaData metaData = conexion.getMetaData();
        String catalogoActual = conexion.getCatalog();
        try (ResultSet rs = metaData.getTables(catalogoActual, null, "%", new String[]{"TABLE"})) {
            while (rs.next()) {
                tablas.add(rs.getString("TABLE_NAME"));
            }
        }
    }
    return tablas;
}
The method uses JDBC DatabaseMetaData to retrieve only tables (not views or system tables) from the current catalog.

Metadata Parameters

  • Catalog: Current database name
  • Schema Pattern: null (all schemas)
  • Table Name Pattern: "%" (all tables)
  • Types: ["TABLE"] (only regular tables)

Error Handling for Refresh

// Controller.java - Line 204
catch (Exception ex) {
    JOptionPane.showMessageDialog(editorView,
        "Error al obtener tablas: " + ex.getMessage(),
        "Error", JOptionPane.ERROR_MESSAGE);
}
Common refresh errors:
  • Connection lost or timed out
  • Insufficient permissions to view metadata
  • Database server unreachable

Table List Display

The table browser shows all available tables:
// SqlEditorView.java - Line 139
modeloListaTablas = new DefaultListModel<>();
listaTablas = new JList<>(modeloListaTablas);
listaTablas.setFont(FUENTE_NORMAL);
listaTablas.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Interactive Features

Double-clicking a table name generates a SELECT query:
// SqlEditorView.java - Line 151
String consulta = "SELECT * FROM " + tablaSeleccionada + " LIMIT 100";
txtConsulta.setText(consulta);
Hovering over the table list shows context:
// SqlEditorView.java - Line 315
listaTablas.setToolTipText("Doble clic para generar SELECT");
When no tables exist:
// SqlEditorView.java - Line 313
listaTablas.setToolTipText("No se encontraron tablas");

Connection State Management

The application maintains connection state throughout the session:

Initialization on Connect

// Controller.java - Line 169
String nombreBD = loginView.getBaseDatosSeleccionada();
editorView.setBaseDeDatos(nombreBD);

List<String> tablas = modelo.obtenerTablasDeBaseDatos();
editorView.actualizarListaTablas(tablas);
When you connect:
  1. Database name is set in the status field
  2. Tables are automatically fetched
  3. Table browser is populated
  4. SQL Editor window opens

Connection Persistence

The connection remains active until:
  • You click Cambiar BD and confirm
  • The application exits
  • A connection error occurs
  • The database server closes the connection
MySQL connections may timeout after extended inactivity. If you encounter connection errors after idle periods, simply reconnect through the login screen.

Background Processing

All connection operations use SwingWorker for non-blocking execution:
// Controller.java - Line 193
SwingWorker<List<String>, Void> worker = new SwingWorker<>() {
    @Override
    protected List<String> doInBackground() throws Exception {
        return modelo.obtenerTablasDeBaseDatos();
    }

    @Override
    protected void done() {
        try {
            List<String> tablas = get();
            editorView.actualizarListaTablas(tablas);
        } catch (Exception ex) {
            // Error handling
        }
    }
};
Background processing ensures the UI remains responsive during network operations and database queries.

Best Practices

Save Queries Before Switching

Copy important queries to an external file before changing databases to avoid losing work.

Refresh After Schema Changes

Always refresh the table list after executing DDL statements (CREATE, ALTER, DROP).

Verify Connection Status

Check the connection status field before executing queries to ensure you’re connected to the correct database.

Use Confirmation Dialogs

Read confirmation dialogs carefully before switching databases to prevent accidental disconnections.

Next Steps

Connecting to MySQL

Learn the initial connection process

Writing Queries

Master SQL query writing and execution

Viewing Results

Understand how to interpret query results

Build docs developers (and LLMs) love