JDBC create table example (PrepareStatement)
In the previous post we saw how to create table with Statement. And now we will create the table with PreapareStatement.
connection = getConnection();
statement = connection.prepareStatement(sqlQuery);
//Executing SQL statement
statement.execute();
We need to include the following dependencies as before.
<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 now let’s create the JDBCExample.java class
package com.javajdbc.example; import org.apache.commons.dbutils.DbUtils; import java.sql.*; 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; PreparedStatement statement = null; final String sql = "CREATE TABLE USER(ID INT NOT NULL, NAME VARCHAR(30) NOT NULL) "; try { connection = getConnection(); statement = connection.prepareStatement(sql); //Executing SQL statement statement.execute(); 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 the output should be:
You are successfully created a connection... Table has been successfully created!