Statements in JDBC are used to execute SQL statements that do not require dynamic parameters passed to the query. Lets see how to create create table using statement in java.
Please note : We will be using MYSql database for executing the SQL statement.
If you are using any other database , then for executing the sample code change the
getConnection() to connect to your database.
We will use the Statement.execute(String sql) method to execute the create table sql.
Create Table SQL
Below is the query that can be fired directly on database to create table
1 2 3 4 5 6 7 |
CREATE TABLE employee_details( id int(5) not null, first_name varchar(255), last_name varchar(255), designation varchar(255), salary int(5) ); |
Now lets see the sample code for firing this SQL using JDBC
Example : Create Table using Statement in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.kscodes.sampleproject.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class StatementCreateTableExample { public static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; public static String CONNECTION_URL = "jdbc:mysql://localhost:3306/mysql"; public static String CONNECTION_USER = "kscodes"; public static String CONNECTION_PASSWORD = "kscodes"; public static void main(String[] args) { String createSql = "CREATE TABLE employee_details(" + " id int(5) not null," + " first_name varchar(255)," + " last_name varchar(255)," + " designation varchar(255), " + " salary int(5))"; try (Connection connection = getConnection(); Statement statement = connection.createStatement()) { statement.execute(createSql); System.out.println("Table created successfully in database"); } catch (SQLException e) { System.out.println("An exception occured while creating Table in database. Exception is :: " + e); } } public static Connection getConnection() { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println("Error while registering JDBC driver"); return null; } Connection connection = null; try { connection = DriverManager.getConnection(CONNECTION_URL, CONNECTION_USER, CONNECTION_PASSWORD); } catch (SQLException e) { System.out.println("Failed to create Connection"); return null; } System.out.println("Connection created Successfully."); return connection; } } |
Output
1 2 |
Connection created Successfully. Table created successfully in database |
Since we have JDK 7, we are using Try-with-resources Statement to handle the resources that are opened.