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
- 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 int employeeID 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.
You can download the full source code of this example here : JdbcCreateTable
How can i use this in main function or should i use this in main ?