This is an old revision of the document!


Connecting to MySQL Databvase
private void btnTestDbConnectionActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        // TODO add your handling code here:
 
        String database = "audina_crm_export_test";
        String table    = "customer";
        String url      = "jdbc:mysql://localhost:3306/audina_crm_export_test";
        String username = "root";
        String password = "";
 
        System.out.println("Connecting to database " + database + "...");
 
        // Connect to DB
        try (Connection connection = (Connection) DriverManager.getConnection(url, username, password)) {
            System.out.println("Database connected!");
 
            String sql = "SELECT * FROM `" + table + "`";
            try {
                //PreparedStatement stmt = connection.prepareStatement(sql);
                Statement stmt = connection.createStatement();
                //stmt.execute(sql);
                ResultSet rs = stmt.executeQuery(sql);
 
                // Spit out data
                while (rs.next()) {
                    int    id = rs.getInt("id");
                    String account_number = rs.getString("account_number");
                    String  company_name = rs.getString("company_name");
                    System.out.println("[" + id + "] " + account_number + ": " + company_name);
                }
 
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                connection.close();
            }
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect to database " + database, e);
        }
 
    }