Retrieve Data From MySql And Display It In A Jtable In Java Using Intellij

Retrieve Data From MySql And Display It In A Jtable In Java Using Intellij

To retrieve data from a MySQL database and display it in a JTable in Java Swing, you can follow these steps:

  1. Connect to the MySQL database using the JDBC driver. You will need to add the JDBC driver to your classpath and create a connection to the database using the DriverManager class.
  2. Create a Statement object from the Connection object. This statement object will be used to execute SQL queries.
  3. Execute a SELECT query to retrieve the data that you want to display in the JTable. You can do this using the executeQuery method of the Statement object.
  4. Retrieve the ResultSet object returned by the executeQuery method. This ResultSet object contains the data retrieved from the database.
  5. Create a DefaultTableModel object and set it as the model for the JTable.
  6. Iterate through the ResultSet object and add each row of data to the DefaultTableModel. You can use the addRow method of the DefaultTableModel to add each row of data as an array of objects.
  7. Set the model of the JTable to the DefaultTableModel.
  1. Create a JScrollPane object and add the JTable to it. This will allow you to scroll through the data if it doesn’t fit on the screen.
  2. Add the JScrollPane to a JFrame or JPanel.
  3. Set the size and location of the JFrame or JPanel as desired.
  4. Make the JFrame or JPanel visible by calling its setVisible method with a parameter of true.

Here is some example code that demonstrates how to do this:

import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class MyTable {
    public static void main(String[] args) {
        // Create a connection to the database
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // Create a table model
        DefaultTableModel model = new DefaultTableModel();

        // Execute a SELECT query and get the result set
        String query = "SELECT * FROM users";
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(query);

            // Get the column names
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            String[] columnNames = new String[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                columnNames[i - 1] = metaData.getColumnName(i);
            }
            model.setColumnIdentifiers(columnNames);

            // Add the rows to the table model
            while (rs.next()) {
                Object[] row = new Object[columnCount];
                for (int i = 1; i <= columnCount; i++) {
                    row[i - 1] = rs.getObject(i);
                }
                model.addRow(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // Create the JTable and set the model
        JTable table = new JTable(model);

        // Add the table to a scroll pane
// Create the scroll pane and add the table to it
        JScrollPane scrollPane = new JScrollPane(table);

// Create the frame and add the scroll pane to it
        JFrame frame = new JFrame("Table Example");
        frame.add(scrollPane);

// Set the size and location of the frame
        frame.setSize(500, 300);
        frame.setLocationRelativeTo(null);

// Make the frame visible
        frame.setVisible(true);
    }
}

To create a MySQL database and table, you can use the following SQL commands:

  1. Create a database:
CREATE DATABASE database_name;
  1. Use the database:
USE database_name;
  1. Create a table:
CREATE TABLE table_name (
  column_name1 datatype constraint,
  column_name2 datatype constraint,
  ...
);

For example, to create a database named “mydatabase” and a table named “users” with columns “id” (integer), “username” (varchar), and “password” (varchar), you can use the following SQL commands:

CREATE DATABASE mydatabase;
USE mydatabase;
CREATE TABLE users (
  id INT NOT NULL AUTO_INCREMENT,
  username VARCHAR(255) NOT NULL,
  password VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

Note that the above SQL commands are just an example and may not be suitable for all situations. You may need to modify them to fit your specific requirements.

To insert rows into a MySQL table, you can use the INSERT statement. Here is an example of how to insert 10 rows into a table named “users”:




INSERT INTO users (username, password) VALUES
  ('user1', 'password1'),
  ('user2', 'password2'),
  ('user3', 'password3'),
  ('user4', 'password4'),
  ('user5', 'password5'),
  ('user6', 'password6'),
  ('user7', 'password7'),
  ('user8', 'password8'),
  ('user9', 'password9'),
  ('user10', 'password10');

This INSERT statement assumes that the “users” table has two columns, “username” and “password”, and that you want to insert values into these columns for each row.

You can also use a VALUES clause for each row if you want to specify different values for each row.

phpMyAdmin SQL Dump

-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 23, 2022 at 11:40 PM
-- Server version: 10.4.20-MariaDB
-- PHP Version: 8.0.8

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `test`
--
CREATE DATABASE IF NOT EXISTS `test` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `test`;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `password`) VALUES(1, 'user1', 'password1');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(2, 'user2', 'password2');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(3, 'user3', 'password3');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(4, 'user4', 'password4');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(5, 'user5', 'password5');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(6, 'user6', 'password6');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(7, 'user7', 'password7');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(8, 'user8', 'password8');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(9, 'user9', 'password9');
INSERT INTO `users` (`id`, `username`, `password`) VALUES(10, 'user10', 'password10');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Source Code – https://github.com/mauricemuteti/Retrieve-Data-From-MySql-And-Display-It-In-A-Jtable-Intellij

Leave a Reply

Your email address will not be published. Required fields are marked *