Slide 1
Slide 2
Slide 3

Create database with java programming (V86)

No Comments

How to Create a Database

A Database is an organized collection of data that can be stored, managed, and retrieved efficiently. In MySQL, a database acts as a container that holds tables, such as Students, Teachers, Products, etc. Each table stores data in rows.

Example: Creating a database in MySQL using Java.



Source Code:

Copied!
import java.sql.DriverManager;
import javax.swing.JOptionPane;
import java.sql.Statement;
    
    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String dbName = txtDbname.getText().trim();  // get text from textbox

        if (dbName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please enter a database name!");
            return;
        }
        Connection conn = null;
        Statement stmt = null;
        try {
            // Load MySQL Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Connect to MySQL without database
            String url = "jdbc:mysql://localhost:3306/?useSSL=false&serverTimezone=Asia/Phnom_Penh";
            String user = "root";   // change to your MySQL username
            String pass = "root";       // change to your MySQL password

            conn = DriverManager.getConnection(url, user, pass);
            stmt = conn.createStatement();

            String sql = "CREATE DATABASE " + dbName;
            stmt.executeUpdate(sql);

            JOptionPane.showMessageDialog(this, "Database '" + dbName + "' created successfully!");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
        } finally {
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }                                                                                                                                                                  

Result:


Watch the video:


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

back to top