Slide 1
Slide 2
Slide 3

Create Table in java programming (V89)

No Comments

How to Create a Table

In SQL, the CREATE TABLE statement is used to create a new table in a database. It defines the table name, columns, their data types, and (optionally) constraints such as PRIMARY KEY, FOREIGN KEY, DEFAULT values, and UNIQUE constraints.

Example: Creating a Table in Java

Properties on jtable à tblFiels


Source Code:

Copied!
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class CreateTableForm extends javax.swing.JFrame {

    /**
     * Creates new form CreateTableForm
     */
    Connection con;
    public CreateTableForm() {
        initComponents();
        loadDatabases(); // load DBs into combo when form opens
         // Setup JTable model
        DefaultTableModel model = (DefaultTableModel) tblFields.getModel();
        tblFields.setModel(model);

        // Create JComboBox with allowed SQL data types
        String[] dataTypes = {"INT", "VARCHAR(50)", "DATE", "DECIMAL(10,2)", "TEXT"};
        JComboBox<String> comboBox = new JComboBox<>(dataTypes);

        // Set the comboBox as editor for the second column (Data Type)
        tblFields.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(comboBox));
    }

    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 btnCreateTableActionPerformed(java.awt.event.ActionEvent evt) {                                               
      // Get selected database from combo box
            String selectedDB = comboDatabases.getSelectedItem().toString();

                String tableName = txtTableName.getText().trim();
        if (tableName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please enter table name");
            return;
        }

        // Validate table name (optional but recommended)
        if (!tableName.matches("[a-zA-Z_][a-zA-Z0-9_]*")) {
            JOptionPane.showMessageDialog(this, "Invalid table name. Use letters, numbers, and underscores only.");
            return;
        }

        // Build SQL dynamically from JTable
        DefaultTableModel model = (DefaultTableModel) tblFields.getModel();
        StringBuilder sql = new StringBuilder("CREATE TABLE `" + tableName + "` (");
        boolean firstFieldAdded = false;

        for (int i = 0; i < model.getRowCount(); i++) {
            String field = model.getValueAt(i, 0) != null ? model.getValueAt(i, 0).toString().trim() : "";
            String type = model.getValueAt(i, 1) != null ? model.getValueAt(i, 1).toString().trim() : "";

            if (!field.isEmpty() && !type.isEmpty()) {
                if (firstFieldAdded) {
                    sql.append(", "); // comma between columns
                }
                sql.append("`").append(field).append("` ").append(type);
                firstFieldAdded = true;
            }
        }

        if (!firstFieldAdded) {
            JOptionPane.showMessageDialog(this, "Please enter at least one field with a valid data type");
            return;
        }

        sql.append(")"); // close parentheses
        // Execute SQL
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/" + selectedDB + "?useSSL=false&serverTimezone=Asia/Phnom_Penh",
                    "root", "root");
                 Statement stmt = con.createStatement()) {

            stmt.executeUpdate(sql.toString());
            JOptionPane.showMessageDialog(this, "Table '" + tableName + "' created successfully in database '" + selectedDB + "'!");
        }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }                                                                                                                                                                

Result:


Watch the video:


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

back to top