JDBC PreparedStatement example to Create a Table
In this example let us learn how to create a table in database via JDBC PrepareStatement. To issue a create statement, calls the PrepareStatement.executeUpdate() method like this :
PreparedStatement preparedStatement = connection.prepareStatement(createTableQuery); // execute create SQL stetement preparedStatement.executeUpdate();
Full example…
package com.simplecode.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCPreparedStatementCreateExample
{
private static final String dbDriver = "oracle.jdbc.driver.OracleDriver";
private static String serverName = "127.0.0.1";
private static String portNumber = "1521";
private static String sid = "XE";
private static final String dbUrl = "jdbc:oracle:thin:@" + serverName + ":"
+ portNumber + ":" + sid;
private static final String dbUser = "system";
private static final String dbPassword = "admin";
public static void main(String[] argc)
{
try
{
createEmployeeTable();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
private static void createEmployeeTable() throws SQLException
{
Connection connection = null;
PreparedStatement prepareStmt = null;
String createTableQuery = "CREATE TABLE EMPLOYEE(USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, CREATED_BY VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID))";
try
{
connection = getDBConnection();
prepareStmt = connection.prepareStatement(createTableQuery);
// execute the SQL statement
prepareStmt.executeUpdate(createTableQuery);
System.out.println("Table EMPLOYEE is created!");
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
if (prepareStmt != null)
{
prepareStmt.close();
}
if (connection != null)
{
connection.close();
}
}
}
private static Connection getDBConnection()
{
Connection dbConnection = null;
try
{
Class.forName(dbDriver);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
try
{
dbConnection=DriverManager.getConnection(dbUrl,dbUser,dbPassword);
return dbConnection;
}
catch (SQLException e)
{
System.out.println("Db "+e.getMessage());
}
return dbConnection;
}
}
