PostgreSQL JDBC: Creating Tables
Summary: in this tutorial, you will learn how to create tables in a PostgreSQL database from a Java program using JDBC.
Creating table program
The following example shows how to create tables in the PostgreSQL database from a Java program:
How it works.
First, construct a CREATE TABLE
statement that creates the products
table:
Second, establish a connection to sales
database on the local PostgreSQL server using the DB
class:
Third, create a Statement
by calling the createStatement()
method of the Connection
object:
Fourth, execute the CREATE
TABLE
statement by calling the executeUpdate()
method.
The try-catch statement will display an error message if any SQLException
occurs.
Since the connect()
and createStatement()
method calls are wrapped in a try-with-resources statement, the Statement
and Connection
will be closed properly.
If you run the program, it’ll create the products
in the sales
database.
Verify the table creation
First, open the Command Prompt on Windows or Terminal on Unix-like systems.
Second, connect to the sales
database on the local PostgreSQL server using the psql
client tool:
It’ll prompt you for a password.
Third, use the \dt
command to show tables in the sales
database:
Output:
The output indicates that the products
table has been created successfully.
Summary
- Call the
executeUpdate()
method of a Statement object to execute aCREATE TABLE
statement to create a new table in the PostgreSQL database.