Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

IAF

JDBC ODBC
Rajnish

Rajnish
[Pick the date]
JDBC Introduction
JDBC Architecture Insert Records
Java Database Connectivity Steps
Test JDBC Driver Installation & Connection Inserting Data into SQL Tables

JDBC ResultSets Select Records


ResultSet and Cursors Retrieving Data from SQL Tables
Types of Result Sets
Result Set Methods
Update Table
Types of JDBC Drivers Update SQL Tables

Type 1: JDBC-ODBC Bridge driver


Type 2: Native-API/partly Java driver Using Prepared
Type
Type
3:
4:
All Java/Net-protocol driver
Native-protocol/all-Java driver
Statements
Using Prepared Statements
Create Table
Create SQL Table

The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database
applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL
statements to almost any relational database. JDBC is a Java API for executing SQL statements and
supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java
code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable
JDBC code to enable remote database access. You will learn how to create a table, insert values into it,
query the table, retrieve results, and update the table with the help of a JDBC Program example.

Although JDBC was designed specifically to provide a Java interface to relational databases, you may
find that you need to write Java code to access non-relational databases as well.

JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change
database engines without changing database code.

JDBC Basics - Java Database


Connectivity Steps
Before you can create a java jdbc connection to the database, you must first import the
java.sql package.

import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be
imported.

1. Loading a database driver,

In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the
Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client
can connect to Database Server through JDBC Driver. Since most of the Database servers support
ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.

try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any
other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!”
);
}

2. Creating a oracle jdbc Connection

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver.
DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the
JDBC drivers that are installed on the system. Its getConnection() method is used to establish a
connection to a database. It uses a username, password, and a jdbc url to establish a connection to the
database and returns a connection object. A jdbc Connection represents a session/connection with a
specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results
are returned. An application can have one or more connections with a single database, or it can have
many connections with different databases. A Connection object provides metadata i.e. information
about the database, tables, and fields. It also contains methods to deal with transactions.

JDBC URL Syntax:: jdbc: <subprotocol>: <subname>


JDBC URL Example:: jdbc: <subprotocol>: <subname>•Each driver has its own subprotocol
•Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol, so the
DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.

try{
Connection
dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn‟t get connection!” );
}

3. Creating a jdbc Statement object,

Once a connection is obtained we can interact with the database. Connection interface defines methods
for interacting with the database via the established connection. To execute SQL statements, you need
to instantiate a Statement object from your connection object by using the createStatement() method.

Statement statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements

Statement: Execute simple sql queries without parameters.


Statement createStatement()
Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters.


PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements.

Callable Statement: Execute a call to a database stored procedure.


CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call
statements.

4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.

Statement interface defines methods that are used to interact with database via the execution of SQL
statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is
executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note:
Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table rows are
retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next()
method is used to successively step through the rows of the tabular results.

ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.

Test JDBC Driver Installation

import javax.swing.JOptionPane;

public class TestJDBCDriverInstallation_Oracle {

public static void main(String[] args) {


StringBuffer output = new
StringBuffer();
output.append(”Testing oracle driver
installation \n”);
try {
String className =
“sun.jdbc.odbc.JdbcOdbcDriver”;
Class driverObject =
Class.forName(className);
output.append(”Driver :
“+driverObject+”\n”);
output.append(”Driver Installation
Successful”);
JOptionPane.showMessageDialog(null,
output);
} catch (Exception e) {
output = new StringBuffer();
output.append(”Driver Installation
FAILED\n”);
JOptionPane.showMessageDialog(null,
output);
System.out.println(”Failed: Driver Error: ” +
e.getMessage());
}
}
}

Download JDBC Sample Code

Java JDBC Connection Example, JDBC Driver


Example
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCDriverInformation {


static String userid=”scott”, password = “tiger”;
static String url = “jdbc:odbc:bob”;
static Connection con = null;
public static void main(String[] args) throws Exception {
Connection con = getOracleJDBCConnection();
if(con!= null){
System.out.println(”Got Connection.”);
DatabaseMetaData meta = con.getMetaData();
System.out.println(”Driver Name :
“+meta.getDriverName());
System.out.println(”Driver Version :
“+meta.getDriverVersion());

}else{
System.out.println(”Could not Get Connection”);
}
}

public static Connection getOracleJDBCConnection(){

try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
} catch(java.lang.ClassNotFoundException e) {
System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url, userid,
password);
} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}

return con;
}

}
Retrieving Data using JDBC Select Query

We can use Java JDBC Select statement in a java program to retrieve the data and display it for the
respective Tables. JDBC returns results in a ResultSet object, so we need to declare an instance of the
class ResultSet to hold our results. Select is the SQL keyword that performs a query. We invoke the
jdbc select query (executequery) method, using the jdbc select data statement as the parameter. The
tabular results of the query are captured in the ResultSet object, results. Note that executeQuery()
always returns a ResultSet although it need not have any rows in it.

The return value for an executeQuery is a ResultSet object containing the results of the query sent to
the DBMS,

To process each row in the ResultSet, we use the next() method. This method moves the pointer
through the rows of data. The ResultSet maintains a cursor pointing to the current row. Because this
cursor is initially positioned before the first row, we must call next() before we can see any rows at all.
Below is a JDBC Program showing the use of executeQuery() to retrieve values from ResultSets using
jdbc programming.

For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC tutorial.

Employee_ID is the primary key which forms a relation between the 2 tables.

CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);

Employees Table:

Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels

Orders Table:

CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);
Prod_ID Product Name Employee_ID
543 Belt 6323
432 Bottle 1234
876 Ring 5678

JDBC SQL Select Example

import javax.swing.JOptionPane;
import java.sql.*;
public class JDBCProgram{

static String userid=”scott”, password = “tiger”;


static String url = “jdbc:odbc:bob”; // String url
= “jdbc:mySubprotocol:myDataSource”; ?
static Statement stmt;
static Connection con;
public static void main(String args[]){

JOptionPane.showMessageDialog(null,”JDBC Programming showi


ng Retrieval of Table Data”);
int choice = -1;

do{
choice = getChoice();
if (choice != 0){
getSelected(choice);
}
}
while ( choice != 0);
System.exit(0);
}

public static int getChoice()


{
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,
“1. Create Employees Table\n”+
“2. Create Products Table\n”+
“3. Insert data into Employees Table\n”+
“4. Insert data into Orders Table\n”+
“5. Retrieve data for Employees Table\n”+
“6. Retrieve data for Orders Table\n”+
“0. Exit\n\n”+
“Enter your choice”);
ch = Integer.parseInt(choice);
return ch;

public static void getSelected(int choice){


if(choice==1){
createEmployees();
}
if(choice==2){
createOrders();
}
if(choice==3){
insertEmployees();
}
if(choice==4){
insertOrders();
}
if(choice==5){
retrieveEmployees();
}
if(choice==6){
retrieveOrders();
}
}

public static Connection getConnection()


{

try {

Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
//Class.forName(”myDriver.ClassName”); ?

} catch(java.lang.ClassNotFoundException e) {
System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
userid, password);

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
return con;
}

/*CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);*/

public static void createEmployees()


{
Connection con = getConnection();

String createString;
createString = “create table Employees (” +
“Employee_ID
INTEGER, ” +
“Name VARCHAR(30))”;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Employees Table
Created”);
}

/*CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);*/

public static void createOrders()


{
Connection con = getConnection();

String createString;
createString = “create table Orders (” +
“Prod_ID INTEGER, ” +
“ProductName VARCHAR(20),
“+
“Employee_ID INTEGER )”;

try {
stmt = con.createStatement();
stmt.executeUpdate(createString);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Orders Table
Created”);
}

/*Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels */
public static void insertEmployees()
{
Connection con = getConnection();

String insertString1, insertString2, insertString3,


insertString4;
insertString1 = “insert into Employees values(6323,
„Hemanth‟)”;
insertString2 = “insert into Employees values(5768,
„Bob‟)”;
insertString3 = “insert into Employees values(1234,
„Shawn‟)”;
insertString4 = “insert into Employees values(5678,
„Michaels‟)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);
stmt.executeUpdate(insertString4);

stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted into
Employees Table”);
}

/* Prod_ID ProductName Employee_ID


543 Belt 6323
432 Bottle 1234
876 Ring 5678
*/
public static void insertOrders()
{
Connection con = getConnection();

String insertString1, insertString2, insertString3,


insertString4;
insertString1 = “insert into Orders values(543,
„Belt‟, 6323)”;
insertString2 = “insert into Orders values(432,
„Bottle‟, 1234)”;
insertString3 = “insert into Orders values(876,
„Ring‟, 5678)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted into
Orders Table”);
}

public static void retrieveEmployees(){


Connection con = getConnection();
String result = null;
String selectString;
selectString = “select * from Employees”;
result =”Employee_ID\t\tName\n”;
try {
stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery(selectString);
while (rs.next()) {
int id = rs.getInt(”Employee_ID”);
String name = rs.getString(”Name”);
result+=id+”\t\t”+ name+”\n”;
}
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null, result);
}

public static void retrieveOrders(){


Connection con = getConnection();
String result = null;
String selectString;
selectString = “select * from Orders”;
result =”Prod_ID\t\tProductName\t\tEmployee_ID\n”;
try {
stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery(selectString);
while (rs.next()) {
int pr_id = rs.getInt(”Prod_ID”);
String prodName =
rs.getString(”ProductName”);
int id = rs.getInt(”Employee_ID”);
result +=pr_id+”\t\t”+
prodName+”\t\t”+id+”\n”;
}
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null, result);
}

}//End of class

JDBC Update Table Example


We can use java jdbc update statements in a java program to update the data for a Table.
Below is a program showing the use of jdbc executeupdate (uses jdbc update query) to update a table.

The return value for a jdbc sql update is an int that indicates how many rows of a table
were updated.

For instance in a statement like

int n = stmt.executeUpdate();

For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC update
table statement.

Employee_ID is the primary key which forms a relation between the 2 tables.

CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);

Employees:

Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels

Orders:

CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);
Prod_ID Product Name Employee_ID
543 Belt 6323
432 Bottle 1234
876 Ring 5678

Below is a jdbc update example

import javax.swing.JOptionPane;
import java.sql.*;
public class JDBCProgram{

static String userid=”scott”, password = “tiger”;


static String url = “jdbc:odbc:bob”;
// String url = “jdbc:mySubprotocol:myDataSource”; ?
static Statement stmt;
static Connection con;
public static void main(String args[]){

JOptionPane.showMessageDialog
(null,”JDBC Programming showing Updation of Table Data”);
int choice = -1;

do{
choice = getChoice();
if (choice != 0){
getSelected(choice);
}
}
while ( choice != 0);
System.exit(0);
}

public static int getChoice()


{
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,
“1. Create Employees Table\n”+
“2. Create Products Table\n”+
“3. Insert data into Employees Table\n”+
“4. Insert data into Orders Table\n”+
“5. Retrieve data for Employees Table\n”+
“6. Retrieve data for Orders Table\n”+
“7. Update Employees Table\n”+
“0. Exit\n\n”+
“Enter your choice”);
ch = Integer.parseInt(choice);
return ch;

public static void getSelected(int choice){


if(choice==1){
createEmployees();
}
if(choice==2){
createOrders();
}
if(choice==3){
insertEmployees();
}
if(choice==4){
insertOrders();
}
if(choice==5){
retrieveEmployees();
}
if(choice==6){
retrieveOrders();
}
if(choice==7){
updateEmployees(); //Uses JDBC Update Statement
}
}

public static Connection getConnection()


{

try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
//Class.forName(”myDriver.ClassName”); ?

} catch(java.lang.ClassNotFoundException e) {
System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
userid, password);

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}

return con;
}

/*CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);*/

public static void createEmployees()


{
Connection con = getConnection();

String createString;
createString = “create table Employees (” +
“Employee_ID INTEGER,
” +
“Name VARCHAR(30))”;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Employees Table Created”);
}

/*CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);*/

public static void createOrders()


{
Connection con = getConnection();

String createString;
createString = “create table Orders (” +
“Prod_ID INTEGER, ” +
“ProductName VARCHAR(20), “+
“Employee_ID INTEGER )”;

try {
stmt = con.createStatement();
stmt.executeUpdate(createString);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Orders Table Created”);
}

/*Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels */
public static void insertEmployees()
{
Connection con = getConnection();

String insertString1, insertString2, insertString3,


insertString4;
insertString1 = “insert into Employees values(6323,
„Hemanth‟)”;
insertString2 = “insert into Employees values(5768,
„Bob‟)”;
insertString3 = “insert into Employees values(1234,
„Shawn‟)”;
insertString4 = “insert into Employees values(5678,
„Michaels‟)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);
stmt.executeUpdate(insertString4);

stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted into Employees
Table”);
}

/* Prod_ID ProductName Employee_ID


543 Belt 6323
432 Bottle 1234
876 Ring 5678
*/
public static void insertOrders()
{
Connection con = getConnection();

String insertString1, insertString2, insertString3,


insertString4;
insertString1 = “insert into Orders values(543,
„Belt‟, 6323)”;
insertString2 = “insert into Orders values(432,
„Bottle‟, 1234)”;
insertString3 = “insert into Orders values(876,
„Ring‟, 5678)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted into Orders
Table”);
}

public static void retrieveEmployees(){


Connection con = getConnection();
String result = null;
String selectString;
selectString = “select * from Employees”;
result =”Employee_ID\t\tName\n”;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(selectString);
while (rs.next()) {
int id = rs.getInt(”Employee_ID”);
String name = rs.getString(”Name”);
result+=id+”\t\t”+ name+”\n”;
}
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null, result);
}

public static void retrieveOrders(){


Connection con = getConnection();
String result = null;
String selectString;
selectString = “select * from Orders”;
result =”Prod_ID\t\tProductName\t\tEmployee_ID\n”;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(selectString);
while (rs.next()) {
int pr_id = rs.getInt(”Prod_ID”);
String prodName =
rs.getString(”ProductName”);
int id = rs.getInt(”Employee_ID”);
result +=pr_id+”\t\t”+
prodName+”\t\t”+id+”\n”;
}
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null, result);
}
public static void updateEmployees(){
Connection con = getConnection();

String updateString1;
updateString1 = “update Employees set name = „hemanthbalaji‟
where Employee_id = 6323″;

try {
stmt = con.createStatement();
stmt.executeUpdate(updateString1);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Updated into Employees
Table”);
}

}//End of class

Java Prepared Statements


Java JDBC Prepared statements are pre-compiled SQL statements. Precompiled SQL is useful if the
same SQL is to be executed repeatedly, for example, in a loop. Prepared statements in java only
save you time if you expect to execute the same SQL over again. Every java sql prepared statement is
compiled at some point. To use a java preparedstatements, you must first create a object by calling the
Connection.prepareStatement() method. JDBC PreparedStatements are useful especially in situations
where you can use a for loop or while loop to set a parameter to a succession of values. If you want to
execute a Statement object many times, it normally reduces execution time to use a
PreparedStatement object instead.

The syntax is straightforward: just insert question marks for any parameters that you’ll be substituting
before you send the SQL to the database. As with CallableStatements, you need to call close() to make
sure database resources are freed as soon as possible. Below is a JDBC Program showing the use of
jdbc prepared statements to insert data into tables using jdbc programming.
You need to supply values to be used in place of the question mark placeholders (if there are any)
before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods
defined in the PreparedStatement class. There is a setXXX method for each primitive type declared in
the Java programming language.

An example of a PreparedStatement object is

PreparedStatement pstmt = con.prepareStatement(”update Orders set pname = ? where Prod_Id =


?”);
pstmt.setInt(2, 100);
pstmt.setString(1, “Bob”);
pstmt.executeUpdate();

An important feature of a PreparedStatement object is that, unlike a Statement object, it is given an


SQL statement when it is created. This SQL statement is sent to the DBMS right away, where it is
compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL
statement that has been precompiled. This means that when the PreparedStatement is executed, the
DBMS can just run the PreparedStatement SQL statement without having to compile it first.

Using Prepared Statements in jdbc, objects can be used for SQL statements with no parameters, you
probably use them most often for SQL statements that take parameters. The advantage of using SQL
statements that take parameters is that you can use the same statement and supply it with different
values each time you execute it.

For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC tutorial.

Employee_ID is the primary key which forms a relation between the 2 tables

CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);

Employees:

Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels

Orders:

CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);
Prod_ID Product Name Employee_ID
543 Belt 6323
432 Bottle 1234
876 Ring 5678

Java JDBC Prepared Statement Example

import javax.swing.JOptionPane;
import java.sql.*;
public class JDBCProgram{

static String userid=”scott”, password = “tiger”;


static String url = “jdbc:odbc:bob”
; // String url = “jdbc:mySubprotocol:myDataSource”;
?
static Statement stmt;
static PreparedStatement pstmt;
static Connection con;
public static void main(String args[]){

JOptionPane.showMessageDial
og(null,”JDBC Programming showing Updation of Table
Data”);
int choice = -1;

do{
choice = getChoice();
if (choice != 0){
getSelected(choice);
}
}
while ( choice != 0);
System.exit(0);
}

public static int getChoice()


{
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,
“1. Create Employees Table\n”+
“2. Create Products Table\n”+
“3. Insert data into Employees Table\n”+
“4. Insert data into Orders Table\n”+
“5. Retrieve data for Employees Table\n”+
“6. Retrieve data for Orders Table\n”+
“7. Update Employees Table\n”+
“8. Update Employees Table Using a Prepared
Statement\n”+
“9. Update many records of Orders Table Using a
Prepared Statement\n”+
“10. List the name of employees who bought CD‟sn”+
“0. Exit\n\n”+
“Enter your choice”);
ch = Integer.parseInt(choice);
return ch;

public static void getSelected(int choice){


if(choice==1){
createEmployees();
}
if(choice==2){
createOrders();
}
if(choice==3){
insertEmployees();
}
if(choice==4){
insertOrders();
}
if(choice==5){
retrieveEmployees();
}
if(choice==6){
retrieveOrders();
}
if(choice==7){
updateEmployees();
}
if(choice==8){
updateEmployeesPrepared();
}
if(choice==9){
updateOrdersPrepared();
}
if(choice==10){
dynamicQuery();
}
}
public static Connection getConnection()
{

try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
//Class.forName(”myDriver.ClassName”); ?

} catch(java.lang.ClassNotFoundException e)
{

System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
userid, password);

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}

return con;
}

/*CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);*/

public static void createEmployees()


{
Connection con = getConnection();

String createString;
createString = “create table Employees (” +
“Employee_ID
INTEGER, ” +
“Name
VARCHAR(30))”;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Employees
Table Created”);
}

/*CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);*/

public static void createOrders()


{
Connection con = getConnection();

String createString;
createString = “create table Orders (” +
“Prod_ID INTEGER, ”
+
“ProductName
VARCHAR(20), “+
“Employee_ID
INTEGER )”;

try {
stmt = con.createStatement();
stmt.executeUpdate(createString);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Orders Table
Created”);
}

/*Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels */
public static void insertEmployees()
{
Connection con = getConnection();

String insertString1, insertString2,


insertString3, insertString4;
insertString1 = “insert into Employees
values(6323, „Hemanth‟)”;
insertString2 = “insert into Employees
values(5768, „Bob‟)”;
insertString3 = “insert into Employees
values(1234, „Shawn‟)”;
insertString4 = “insert into Employees
values(5678, „Michaels‟)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);
stmt.executeUpdate(insertString4);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted
into Employees Table”);
}

/* Prod_ID ProductName Employee_ID


543 Belt 6323
432 Bottle 1234
876 Ring 5678
*/
public static void insertOrders()
{
Connection con = getConnection();

String insertString1, insertString2,


insertString3, insertString4;
insertString1 = “insert into Orders values(543,
„Belt‟, 6323)”;
insertString2 = “insert into Orders values(432,
„Bottle‟, 1234)”;
insertString3 = “insert into Orders values(876,
„Ring‟, 5678)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted
into Orders Table”);
}

public static void retrieveEmployees(){


Connection con = getConnection();
String result = null;
String selectString;
selectString = “select * from Employees”;
result =”Employee_ID\t\tName\n”;
try {
stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery(selectString);
while (rs.next()) {
int id = rs.getInt(”Employee_ID”);
String name =
rs.getString(”Name”);
result+=id+”\t\t”+ name+”\n”;
}
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null, result);
}
public static void retrieveOrders(){
Connection con = getConnection();
String result = null;
String selectString;
selectString = “select * from Orders”;
result
=”Prod_ID\t\tProductName\t\tEmployee_ID\n”;
try {
stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery(selectString);
while (rs.next()) {
int pr_id =
rs.getInt(”Prod_ID”);
String prodName =
rs.getString(”ProductName”);
int id = rs.getInt(”Employee_ID”);
result +=pr_id+”\t\t”+
prodName+”\t\t”+id+”\n”;
}
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null, result);
}

public static void updateEmployees(){


Connection con = getConnection();

String updateString1;
updateString1 = “update Employees set name =
„hemanthbalaji‟
where Employee_id = 6323″;

try {
stmt = con.createStatement();
stmt.executeUpdate(updateString1);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Updated
into Employees Table”);
}

public static void updateEmployeesPrepared(){


Connection con = getConnection();
// create prepared statement
try {
pstmt = con.prepareStatement
(”update Employees set name = ? where Employee_Id = ?”);
pstmt.setString(1, “hemanthbob”); //Note index
starts with 1
pstmt.setInt(2, 6323);

pstmt.executeUpdate();

pstmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Updated
into Employees Table”);
}

public static void updateOrdersPrepared(){

int [] productIds = {543, 432, 876};


String [] productNames = {”cds”, “dvds”,
“Espresso”};
int len = productNames.length;

Connection con = getConnection();

try {
pstmt = con.prepareStatement
(”update Orders set productname = ? where Prod_Id = ?”);
for(int i = 0; i < len; i++) {
pstmt.setInt(2, productIds[i]);
pstmt.setString(1,
productNames[i]);
pstmt.executeUpdate();
}
pstmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Updated
into Orders Table”);
}

public static void dynamicQuery(){


Connection con = getConnection();
String result = null;
String selectString;
selectString = “select Employees.name from
Employees,
Orders where productname = „cds‟ ” +
“and Employees.employee_id =
Orders.employee_id “;
result =”Name\n”;
try {
stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery(selectString);
while (rs.next()) {
String name =
rs.getString(”Name”);
result+=name+”\n”;
}
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null, result);
}

}//End of class
ResultSet and Cursors
The rows that satisfy a particular query are called the result set. The number of rows returned in a
result set can be zero or more. A user can access the data in a result set using a cursor one row at a
time from top to bottom. A cursor can be thought of as a pointer to the rows of the result set that has
the ability to keep track of which row is currently being accessed. The JDBC API supports a cursor to
move both forward and backward and also allowing it to move to a specified row or to a row whose
position is relative to another row. The JDBC Resultset example is shown in the next sections to follow.

Types of Result Sets


The ResultSet interface provides methods for retrieving and manipulating the results of executed
queries, and ResultSet objects can have different functionality and characteristics. These characteristics
are result set type, result set concurrency, and cursor holdability.

The type of a ResultSet object determines the level of its functionality in two areas: the ways in which
the cursor can be manipulated, and how concurrent changes made to the underlying data source are
reflected by the ResultSet object.

The sensitivity of the ResultSet object is determined by one of three different ResultSet types:

 TYPE_FORWARD_ONLY — the result set is not scrollable i.e. the cursor moves only
forward, from before the first row to after the last row.
 TYPE_SCROLL_INSENSITIVE — the result set is scrollable; its cursor can move both
forward and backward relative to the current position,
and it can move to an absolute position.
 TYPE_SCROLL_SENSITIVE — the result set is scrollable; its cursor can move both forward
and backward relative to the current position, and it can move to an absolute position.

Before you can take advantage of these features, however, you need to create a scrollable
ResultSet object. The following line of code illustrates one way to create a scrollable ResultSet
object:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,


ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(”…..”);

The first argument is one of three constants added to the ResultSet API to indicate the type of a
ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and
TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for
specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and
CONCUR_UPDATABLE. If you do not specify any constants for the type and updatability of a
ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and
CONCUR_READ_ONLY.

Result Set Methods


When a ResultSet object is first created, the cursor is positioned before the first row. To move
the cursor, you can use the following methods:

 next() - moves the cursor forward one row. Returns true if the cursor is now positioned on a
row and false if the cursor is positioned after the last row.
 previous() - moves the cursor backwards one row. Returns true if the cursor is now
positioned on a row and false if the cursor is positioned before the first row.
 first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is
now positioned on the first row and false if the ResultSet object
does not contain any rows.
 last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is
now positioned on the last row and false if the ResultSet object
does not contain any rows.
 beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If
the ResultSet object does not contain any rows, this method has
no effect.
 afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the
ResultSet object does not contain any rows, this method has no effect.
 relative(int rows) - moves the cursor relative to its current position.
 absolute(int n) - positions the cursor on the n-th row of the ResultSet object.

JDBC Driver Types


JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
4 types of jdbc drivers are elaborated in detail as shown below:
Type 1 JDBC Driver
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver.
ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental
use or when no other alternative is available.
Type 1: JDBC-ODBC Bridge
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the databases ODBC
drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then
to the database, and this applies even in the reverse process. They are the slowest of all driver
types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Type 2 JDBC Driver
Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls
into database-specific calls i.e. this driver is specific to a particular database. Some distinctive
characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native
api.
Type 2: Native api/ Partly Java Driver
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than
that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used
for the Internet.
2. Like Type 1 drivers, its not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.
Type 3 JDBC Driver
All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server. The
middle-tier then translates the request to the database. If the middle-tier server can in turn use
Type1, Type 2 or Type 4 drivers.
Type 3: All Java/ Net-Protocol Driver
Advantage
1. This driver is server-based, so there is no need for any vendor database library to be present
on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query
results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset may take
longer, since the data comes through the backend server.
Type 4 JDBC Driver
Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database server.

Type 4: Native-protocol/all-Java driver


Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java
to achieve platform independence and eliminate deployment administration issues. It is most
suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers dont have to translate
database requests to ODBC or a native connectivity interface or to pass the request on to
another server, performance is typically quite good.
3. You dont need to install special software on the client or server. Further, these drivers can
be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
Inserting Data into SQL Tables
We will insert data into the table’s Employees and Orders as created in the previous tutorial, one row at
a time, supplying the information to be stored in each column of that row using a jdbc insert query
statement. The values to be inserted into the columns are listed in the same order that the columns
were declared when the table was created. Below is a JDBC Program showing the use of
executeUpdate() to create a table and insert row into using java jdbc insert data statement.

For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC tutorial
for insert in jdbc insert query.

Employee_ID is the primary key which forms a relation between the 2 tables.

CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);

Employees:

Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels

Orders:

CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);

Prod_ID Product Name Employee_ID


543 Belt 6323
432 Bottle 1234
876 Ring 5678

Iinsert using JDBC Insert Statement


import javax.swing.JOptionPane;
import java.sql.*;
public class JDBCProgram{
//JDBC Insert Example
static String userid=”scott”, password = “tiger”;
static String url = “jdbc:odbc:bob”;
// String url = “jdbc:mySubprotocol:myDataSource”; ?
static Statement stmt;
static Connection con;
public static void main(String args[]){

JOptionPane.showMessageDialog
(null,”JDBC Programming showing Insertion of Table Data”);
int choice = -1;

do{
choice = getChoice();
if (choice != 0){
getSelected(choice);
}
}
while ( choice != 0);
System.exit(0);
}

public static int getChoice()


{
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,
“1. Create Employees Table\n”+
“2. Create Products Table\n”+
“3. Insert data into Employees Table\n”+
“4. Insert data into Products Table\n”+
“0. Exit\n\n”+
“Enter your choice”);
ch = Integer.parseInt(choice);
return ch;

public static void getSelected(int choice){


if(choice==1){
createEmployees();
}
if(choice==2){
createOrders();
}
if(choice==3){
insertEmployees();
}
if(choice==4){
insertOrders();
}
}

public static Connection getConnection()


{

try {
Class.forName
(”sun.jdbc.odbc.JdbcOdbcDriver”);
//Class.forName(”myDriver.ClassName”); ?

} catch(java.lang.ClassNotFoundException e) {
System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
userid, password);

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}

return con;
}

/*CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);*/

public static void createEmployees()


{
Connection con = getConnection();

String createString;
createString = “create table Employees (” +
“Employee_ID INTEGER,
” +
“Name VARCHAR(30))”;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Employees Table
Created”);
}

/*CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);*/

public static void createOrders()


{
Connection con = getConnection();

String createString;
createString = “create table Orders (” +
“Prod_ID INTEGER, ” +
“ProductName
VARCHAR(20), “+
“Employee_ID INTEGER
)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(createString);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Orders Table
Created”);
}
/*Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels */
public static void insertEmployees()
{
Connection con = getConnection();

String insertString1, insertString2, insertString3,


insertString4;
insertString1 = “insert into Employees values(6323,
„Hemanth‟)”;
insertString2 = “insert into Employees values(5768,
„Bob‟)”;
insertString3 = “insert into Employees values(1234,
„Shawn‟)”;
insertString4 = “insert into Employees values(5678,
„Michaels‟)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);
stmt.executeUpdate(insertString4);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted into
Employees Table”);
}

/* Prod_ID ProductName Employee_ID


543 Belt 6323
432 Bottle 1234
876 Ring 5678
*/
public static void insertOrders()
{
Connection con = getConnection();
String insertString1, insertString2, insertString3,
insertString4;
insertString1 = “insert into Orders values(543,
„Belt‟, 6323)”;
insertString2 = “insert into Orders values(432,
„Bottle‟, 1234)”;
insertString3 = “insert into Orders values(876,
„Ring‟, 5678)”;

try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2);
stmt.executeUpdate(insertString3);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” +
ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Data Inserted into Orders
Table”);
}

}//End of class

Create SQL Table


Tables are composed of rows and columns. Each row represents a record in the database. Columns are
also known as fields, or attributes. You can relate one database table to another by causing a given
column in the table to derive its value from the value of a column in another table. If the tables had no
columns in common, then there would be no way to relate them to one another. Because you can link
tables together you can easily extract data from multiple tables with a single query, if your query
mechanism supports this type of query.
In order to integrate your tables into a single database, you’ll need to ensure that each table has a
column that contains a value unique to that table. Such a column is called a key. Below is a JDBC
Program showing the use of executeUpdate() to create a table jdbc programming.

For my website I am creating the following 2 tables (Employee, Orders)

Employee_ID is the primary key which forms a relation between the 2 tables.

CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);

Employees:

Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels

Orders:

CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);

Prod_ID Product Name Employee_ID


543 Belt 6323
432 Bottle 1234
876 Ring 5678
import javax.swing.JOptionPane;
import java.sql.*;
public class JDBCProgram{

static String userid=”scott”, password = “tiger”;


static String url = “jdbc:odbc:bob”;
// String url = “jdbc:mySubprotocol:myDataSource”; ?
static Statement stmt;
static Connection con;
public static void main(String args[]){

JOptionPane.showMessageDialog
(null,”JDBC Programming showing Creation of Table‟s”);
int choice = -1;

do{
choice = getChoice();
if (choice != 0){
getSelected(choice);
}
}
while ( choice != 0);
System.exit(0);
}

public static int getChoice()


{
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,
“1. Create Employees Table\n”+
“2. Create Products Table\n”+
“0. Exit\n\n”+
“Enter your choice”);
ch = Integer.parseInt(choice);
return ch;

public static void getSelected(int choice){


if(choice==1){
createEmployees();
}
if(choice==2){
createOrders();
}
}

public static Connection getConnection()


{

try {
Class.forName
(”sun.jdbc.odbc.JdbcOdbcDriver”); //Class.forName(”myDriver.ClassName”); ?

} catch(java.lang.ClassNotFoundException e) {
System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
userid, password);

} catch(SQLException ex) {
System.err.println(”SQLException: ” + ex.getMessage());
}

return con;
}

/*CREATE TABLE Employees (


Employee_ID INTEGER,
Name VARCHAR(30)
);*/
public static void createEmployees()
{
Connection con = getConnection();

String createString;
createString = “create table Employees (” +
“Employee_ID INTEGER, ” +
“Name VARCHAR(30))”;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” + ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Employees Table Created”);
}

/*CREATE TABLE Orders (


Prod_ID INTEGER,
ProductName VARCHAR(20),
Employee_ID INTEGER
);*/

public static void createOrders()


{
Connection con = getConnection();

String createString;
createString = “create table Orders (” +
“Prod_ID INTEGER, ” +
“ProductName VARCHAR(20), “+
“Employee_ID INTEGER )”;

try {
stmt = con.createStatement();
stmt.executeUpdate(createString);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println(”SQLException: ” + ex.getMessage());
}
JOptionPane.showMessageDialog(null,”Orders Table Created”);
}

}//End of class

You might also like