Slide 1
Slide 2
Slide 3

Select database from java programming (V87)

No Comments

How to Select a Database

In MySQL, selecting a database means choosing the database that you want to work with on the database server (such as MySQL or SQL Server) before executing SQL queries.

Example: Selecting a database in Java.

 

Source Code:

Copied!
    import java.sql.*;
    import javax.swing.*;
 
    Connection con;
    public DatabaseSelector() {
        initComponents();
        loadDatabases(); // load DBs into combo when form opens
    }
    private void loadDatabases() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Connect to MySQL server (no specific DB yet)
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/?useSSL=false&serverTimezone=Asia/Phnom_Penh",
                "root",   // your MySQL username
                "root"        // your MySQL password
            );

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SHOW DATABASES");

            // Clear old items first
            comboDatabases.removeAllItems();

            while (rs.next()) {
                comboDatabases.addItem(rs.getString(1)); // add DB name
            }

            rs.close();
            stmt.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String dbName = (String) comboDatabases.getSelectedItem();
        if (dbName != null) {
            // Example: connect to that database
            try {
                Connection dbCon = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/" + dbName + "?useSSL=false&serverTimezone=Asia/Phnom_Penh",
                    "root",
                    "root"
                );
                JOptionPane.showMessageDialog(this, "You selected database: " + dbName);
                dbCon.close();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Connection failed: " + ex.getMessage());
            }
        }
    }                                                                                                                                                                

Result:


Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top