sql

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.

2. Project Set-up

  • Project Structure
    • It is an Eclipse project
    • Notice the use of the “mysql-connector-java” jar for connecting to the database from Eclipse

      Figure 1: project structure
      Figure 1: project structure
  • Database Creation
    • For this example we will connect to a MySQL relational database
    • Table Schema
      Let’s create a simple table: Employee_Details with the following schema.

      firstName varchar(20)lastName varchar(20)age intemployeeID int not null

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.

CreateTable.java

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;

try{
  Connection conn = getConnection();
  stmt = conn.createStatement();
  stmt.executeUpdate(tableDropQuery);
  int result = stmt.executeUpdate(tableCreateQuery);
  if(result == 0)
     System.out.println("Table created successfully!");
  else
     System.out.println("Oops!");
   
}catch(Exception e){
  e.printStackTrace();
} finally{
  if(stmt!=null)
     stmt.close();
  if(conn!=null)
     conn.close();
}

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.

Download
You can download the full source code of this example here : JdbcCreateTable

Joormana Brahma

She has done her graduation in Computer Science and Technology from Guwahati, Assam. She is currently working in a small IT Company as a Software Engineer in Hyderabad, India. She is a member of the Architecture team that is involved in development and quite a bit of R&D. She considers learning and sharing what has been learnt to be a rewarding experience.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Chris
Chris
6 years ago

How can i use this in main function or should i use this in main ?

Back to top button