Creating a Table with Java JDBC Statement

In Java, the JDBC (Java Database Connectivity) API provides a standard way to interact with databases. With JDBC, you can perform various database operations, including creating tables. In this tutorial, we’ll explore how to create a table using Java JDBC statements.

This example code uses the PostgreSQL JDBC driver for establishing a connection and creating a table, so we need the PostgreSQL dependency in our pom.xml file:

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.6.0</version>
</dependency>

SQL Statement for Creating a Table

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    age INT,
    salary DECIMAL(10,2)
)

Creating a Table Using JDBC Statement

public class CreateTable {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:postgresql://localhost:5432/mydatabase";
        String username = "myuser";
        String password = "mypassword";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
            Statement statement = connection.createStatement();

            String createTableQuery = "CREATE TABLE employees (" +
                    "id SERIAL PRIMARY KEY, " +
                    "name VARCHAR(50) NOT NULL, " +
                    "age INT, " +
                    "salary DECIMAL(10,2)" +
                    ")";

            statement.executeUpdate(createTableQuery);

            System.out.println("Table created successfully!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Output

$ Table created successfully!

Conclusion

In this tutorial, we’ve learned how to create a table using Java JDBC statements. We established a database connection, executed an SQL statement to create a table, and verified the output. JDBC provides a powerful and flexible way to interact with databases in Java, allowing you to perform various database operations programmatically.