JDBC create table example (Statement)
In this example we can see how we can create a table with jdbc statement. In the pom.xml we need to add following two dependencies:
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> </dependencies> [addToAppearHere]
And following configuration class for jdbc driver name, url, username and password:
package com.javajdbc.example; public final class DatabaseConfiguration { /** * Mysql driver class name */ public static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver"; /** * The URL */ public static final String URL = "jdbc:mysql://localhost:3306/techblog"; /** * The username */ public static final String USERNAME = "root"; /** * The password */ public static final String PASSWORD = "root"; private DatabaseConfiguration() { // no initialization } }
And the final step is to create the JDBCExample.java
package com.javajdbc.example; import org.apache.commons.dbutils.DbUtils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import static com.javajdbc.example.DatabaseConfiguration.*; public class JDBCExample { public static void main(String[] argv) { final JDBCExample jdbcExample = new JDBCExample(); final Connection connection = jdbcExample.getConnection(); if (connection != null) { System.out.println("You are successfully created a connection..."); } else { System.out.println("Failed to create a connection..."); } jdbcExample.createUserTable(); } private void createUserTable() { Connection connection = null; Statement statement = null; final String sql = "CREATE TABLE USER(ID INT NOT NULL, NAME VARCHAR(30) NOT NULL) "; try { connection = getConnection(); statement = connection.createStatement(); //Executing SQL statement statement.execute(sql); System.out.println("Table has been successfully created!"); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DbUtils.closeQuietly(statement); DbUtils.closeQuietly(connection); } } /** * * @return the jdbc connection */ private Connection getConnection() { try { //Loading the driver class Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println(e); } Connection connection = null; try { //Attempts to establish a connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { System.out.println(e); } return connection; } }
And you should see following output:
You are successfully created a connection... Table has been successfully created!