Java Database Connectivity(JDBC) API provide a set of classes and interfaces that allow a Java application to connect to a database and
execute SQL statements such as -
In this article, we are going to explain how to create a table within the Oracle database using its Type-4 JDBC thin driver and
this driver does not
require DataSourceName(DSN) to connect to the Oracle database.
Note : The JDBC classes and interfaces are available in java.sql and javax.sql packages.
Steps to create a table in JDBC -
Loading and registering database driver to connect our Java application with a database.
Class.forName("oracle.jdbc.driver.OracleDriver");
In the upcoming example, we are going to create a table within the Oracle database using its JDBC Type-4 thin driver.
Creating a connection between the Java program and the Oracle database.
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott", "tiger");
In the upcoming example, we are using Oracle's thin JDBC driver to create a table, where -
localhost refers to our local computer where the Oracle database server is running.
1521 is the port number to connect to the database.
XE is the Service Name for connecting to Oracle Express Edition Database.
scott is our username to connect to the Oracle database and tiger is its password set at the time of installation of Oracle database, you would need to enter the username and password set by you.
Creating a Statement object to excute SQL statements
Statement stmt = con.createStatement();
Creating a Statement object to using createStatement() method of Connection interface.
Executing a SQL query using Statement object.
int count = stmt.executeUpdate(query);
query is a String object which specifies the SQL query to execute.
Closing the database connection
con.close();
con is a Connection reference used to close the connection with the database.
Advertisement
Creating a table with CREATE SQL statement using JDBC
// How to create a table using JDBC API
import java.sql.*;
class A
{
public static void main(String... ar)
{
try
{
//SQL CREATE TABLE query
String query = "CREATE TABLE MyTable ("
+ "ID int,"
+ "FirstName varchar(30),"
+ "LastName varchar(30),"
+ "Age int )";
//Loading and registering Oracle database thin driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Creating a connection between Java program and Oracle database.
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott", "tiger");
//Creating a Statement object to excute SQL statements
Statement stmt = con.createStatement();
//Executing a SQL query using Statement object.
int count = stmt.executeUpdate(query);
System.out.println("Total rows updated "+ count);
}
catch(Exception e)
{
System.out.println(e);
}
} //main method() ends
} //class definition ends
After executing the program, you are going to have an empty table named MyTable within the Oracle database, which may look like this -