JDBC Create Table example

1. Introduction

This article presents a simple example of creating a database table. We will be using the JDBC (Java DataBase Connectivity) API to connect to a relational database and execute a SQL query to create a table using the Statement object. Note that one could use any of the methods offered by the Statement object viz. execute(String sql), executeQuery(String sql) or executeUpdate(String sql) to execute table creation SQL query but we will use ‘executeUpdate()’ which is considered most appropriate for DDL statements. The example code is available for download at the end of the article for reference.

Want to be a JDBC Master ?
Subscribe to our newsletter and download the JDBC Ultimate Guide right now!
In order to help you master database programming with JDBC, we have compiled a kick-ass guide with all the major JDBC features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

2. Project Set-up

3. Code Snippet

The following shows the code snippet to create a table using JDBC Statement. Note that try..catch.. etc. have been removed for the sake of brevity.

CreateTable.java first drops any existing table with the name Employee_Details and then creates the table.


String tableDropQuery = "DROP TABLE IF EXISTS Employee_Details";
String tableCreateQuery = "CREATE TABLE Employee_Details (firstName VARCHAR(20),lastName VARCHAR(20),age INT,employeeID INT NOT NULL";
Statement stmt = null;
  Connection conn = getConnection();
  stmt = conn.createStatement();
  int result = stmt.executeUpdate(tableCreateQuery);
  if(result == 0)
     System.out.println("Table created successfully!");
}catch(Exception e){
} finally{

4. Conclusion

This brings us to the end of the article. Hope it was a useful read.
As promised, the example code is available for download below.

You can download the full source code of this example here : JdbcCreateTable
Exit mobile version