• September 28, 2014
  • JDBC
  • Comments Off on JDBC Statement creates a table example

JDBC Statement creates a table example

The JDBC statement is used to execute queries against the database. Let us study JDBC Statement by create table example.

Example:

JDBCTest.java

import java.sql.Connection;
import java.sql.Statement;
import com.javawithease.util.JDBCUtil;
 
/**
 * This class is used to create a table in DB.
 * @author javawithease
 */
public class JDBCTest {
	public static void main(String args[]){
		Connection conn = null;
		Statement statement = null;
 
		String query = "create table EMPLOYEE("
			+ "EMPLOYEE_ID NUMBER(5) NOT NULL, "
			+ "NAME VARCHAR(20) NOT NULL, "
			+ "SALARY NUMBER(10) NOT NULL, "
			+ "PRIMARY KEY (EMPLOYEE_ID) )";
 
		try{			
			//get connection
			conn = JDBCUtil.getConnection();
 
			//create statement
			statement = conn.createStatement();
 
			//execute query
			statement.execute(query);
 
			//close connection
			statement.close();
			conn.close();
 
			System.out.println("Table created successfully.");
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
}

JDBCUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
 
/**
 * This is a utility class for JDBC connection.
 * @author jawithease
 */
public class JDBCUtil {
	//JDBC and database properties.
	private static final String DB_DRIVER = 
		           "oracle.jdbc.driver.OracleDriver";
	private static final String DB_URL = 
		        "jdbc:oracle:thin:@localhost:1521:XE";
	private static final String DB_USERNAME = "system";
	private static final String DB_PASSWORD = "oracle";
 
	public static Connection getConnection(){
		Connection conn = null;
		try{
			//Register the JDBC driver
			Class.forName(DB_DRIVER);
 
			//Open the connection
			conn = DriverManager.
			getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
 
			if(conn != null){
			   System.out.println("Successfully connected.");
			}else{
			   System.out.println("Failed to connect.");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}	
}

Output:

Successfully connected.
Table created successfully.

Download this example.
 
Next Topic: JDBC Statement inserts a record example.
Previous Topic: JDBC Statement interface.

Related Topics:

JDBC Statement creates a table example.
JDBC Statement inserts a record example.
JDBC Statement updates a record example.
JDBC Statement select records example.
JDBC Statement deletes a record example.
JDBC Statement batch update example.

 


Comments are closed.