JDBC PreparedStatement – Создание таблицы (с Maven)

Создание таблицы с использованием PreparedStatement не отличается от создания таблицы с использованием Statement, поэтому в данном примере подготовки запроса не происходит.

Минимально необходимый код:

Connection  connection = getConnection();	
PreparedStatement statement = connection.prepareStatement(QUERY);
statement.executeUpdate();

Полный код создания таблицы:

package statements;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class StatementsExample {
  private static final String DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
    private static final String CONNECTION_STRING = "jdbc:derby:derbyDB;create=true";
    private static final String QUERY = "CREATE TABLE USERS_TABLE ("
    		+ "ID INT NOT NULL, "
    		+ "USER_NAME VARCHAR(255) NOT NULL, "
    		+ "PRIMARY KEY (ID)"
    		+ ")";
  
  private void run() throws SQLException {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
      connection = getConnection();	
      statement = connection.prepareStatement(QUERY);
      statement.executeUpdate();
      
      System.out.println("Table created successfully");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (statement != null) {
        statement.close();
      }
      if (connection != null) {
        connection.close();
      }
    }
  }
  
  private Connection getConnection() throws ClassNotFoundException, SQLException {
    Class.forName(DRIVER_NAME);
    Connection connection = DriverManager.getConnection(CONNECTION_STRING);
    return connection;
  }
  
  public static void main(String[] args) {
    StatementsExample app = new StatementsExample();
    try {
      app.run();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

}

Зависимости можно получить через Apache Maven, pom.xml приведен ниже:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ru.mydesignstudio</groupId>
  <artifactId>statements</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.12.1.1</version>
        </dependency>
    </dependencies>
</project>