Apache Derby Java Notes

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

Thinking Machines – Java DB Page 1

Prerequisite : java 1.8


For Windows Download Apache Derby from
http://redrockdigimark.com/apachemirror//db/derby/db-derby-10.14.1.0/db-derby-10.14.1.0-
bin.zip
After downloading the zip file, extract it to some folder.
After extraction, copy the folder that contains the bin folder, (db-derby-10.14.1.0-bin) to c:\ and rename
it to java-derby
go to control panel → system → advanced system settings → environment variables → in the user
variables section and system variables section edit the PATH environment variable and add
;c:\java-derby\bin to it.
Now in both the sections add a new environment variable named as DERBY_HOME with value
as c:\java-derby

Now go to command prompt and create a folder c:\javadb , move into it and type
startnetworkserver to start the server. Following is the screen shot.

The server is ready to accept request at port number 1527


Note : if a firewall prompt appears, select allow. If you face problems, turn of the firewall.
Now open another command prompt and move to c:\javadb
in c:\javadb folder create a folder named as db

But don't move into it. We will ask the Apache Derby server to create database files in the db folder.
While staying in the c:\javadb folder type ij

Now you will see a derby prompt. Type


connect 'jdbc:derby://localhost:1527/db/tmplacements;create=true';
If you have done everything correctly, then on the next line the derby prompt will appear as follows

Now the database structure has been created in db folder. We don't care how it is done. Type quit; to
exit from the apache derby client.
Thinking Machines – Java DB Page 2

Now let us create tables. Let us again run the apache derby (ij) client tool and connect. This time we
don't need to specify (create=true) option as the database has already been created.

Connect and type the sql statements as shown below

the above SQL Statements are

create table country


(code int primary key generated always as identity (start with 1,increment by 1),
name char(30) not null unique);

create table state


(code int primary key generated always as identity (start with 1,increment by 1),
name char(30) not null unique,
country_code int not null,
foreign key (country_code) references country);
Thinking Machines – Java DB Page 3

create table city


(code int primary key generated always as identity (start with 1,increment by 1),
name char(30) not null unique,
state_code int not null,
foreign key (state_code) references state);

Now let us perform some CRUD Operations on the created table.

Note : In this document, I won't be terminating the sql statements with ; but you have to do so
on the apache derby client tool. You should also try to insert, update or delete records because of
which primary key or not null or foreign key constraints would be voilated. Following is a screen
shot of one such example, where I tried to insert two countries with same name.
Thinking Machines – Java DB Page 4

Following are the sql statements to perform CRUD Operation, type carefully and learn things on your
own.

insert into country (name) values ('India');


insert into country (name) values ('USA');
select * from country;

Now you need to remember the codes of country, in my case India got 1 and USA got 3 (Why 3 and not
2, because, I tried to insert India again, it failed because of unique constraint applied on name coulmn,
but the value (2) got used up while trying to insert 'India' with code 2 and hence the next country
inserted got the code of 2. So while inserting states, I will be providing the country_code as 1 and 3.
You may have to vary that part according to whatever you have done while inserting records in country
table.

insert into state (name,country_code) values ('Maharashtra',1);


insert into state (name,country_code) values ('Madhya Pradesh',1);
insert into state (name,country_code) values ('Florida',3);
insert into state (name,country_code) values ('Texas',3);
insert into state (name,country_code) values ('xyz',3);
select * from state

update state set name='Karnatakaaa',country_code=1 where name='xyz'


select * from state
See the code and remember it for delete statement. In my case it is 101

delete from state where code=101

select * from state

select code,name from state


select code,name as "State" from state

Note : try inserting a state with a country code that doesn't exist
Note that while adding cities, the state code of Maharashtra is 1, Madhya Pradesh is 2, Florida is 3 and
Texas is 4

insert into city (name,state_code) values('Mumbai',1)


insert into city (name,state_code) values('Pune',1)
insert into city (name,state_code) values('Bhopal',2)
insert into city (name,state_code) values('Dewas',2)
insert into city (name,state_code) values('Ujjain',2)
insert into city (name,state_code) values('Indore',2)
insert into city (name,state_code) values('Holywood',3)
insert into city (name,state_code) values('Longwood',3)
insert into city (name,state_code) values('Plant City',3)
insert into city (name,state_code) values('Arlington',4)
Thinking Machines – Java DB Page 5

select * from city


select * from city where state_code=1
select * from state where country_code=1
select * from country where name='India'
select * from state where name='Maharashtra'
select * from city where state_code=(select code from state where name='Maharashtra')
select * from state where country_code=(select code from country where name='India')
select code from state where country_code=(select code from country where name='India')

select * from city where state_code=(select code from state where country_code=(select code from
country where name='India'))

select * from city where state_code in (select code from state where country_code=(select code from
country where name='India'))

Note : It is better that you write down the output of the next sql statement.

select * from state,country

[SPACE FOR OUTPUT OF THE ABOVE SQL STATEMENT]

Notice that the output is useless, wrong information is being presented. Before looking at the next SQL
Statement, mark the records that we would like to see (4 out of the 8 presented)

select * from state,country where state.country_code=country.code

select state.code,state.name,country.code,country.name from state,country where


state.country_code=country.code

select state.name as "State",country.name as "Country" from state,country where


state.country_code=country.code
Thinking Machines – Java DB Page 6

select city.name as "City",state.name as "State",country.name as "Country" from city,state,country


where city.state_code=state.code and state.country_code=country.code

select city.name as "City",state.name as "State",country.name as "Country" from city,state,country


where city.state_code=state.code and state.country_code=country.code order by city.name

select city.name as "City",state.name as "State",country.name as "Country" from city,state,country


where city.state_code=state.code and state.country_code=country.code order by
country.name,state.name,city.name

select state.code,state.name,country.code,country.name from state


inner join country on state.country_code=country.code

select city.name as "City",state.name as "State",country.name as "Country" from city inner join state on
city.state_code=state.code inner join country on state.country_code=country.code

select city.name as "City",state.name as "State",country.name as "Country" from city inner join state on
city.state_code=state.code inner join country on state.country_code=country.code order by city.name
desc,state.name,country.name

select count(*) from country


select count(*) as cnt from country

insert into country (name) values ('Germany')


select * from country
Note : remember the code alloted to Germany

select * from state left join country on state.country_code=country.code

select * from country left join state on country.code=state.country_code

select * from state right join country on state.country_code=country.code

select * from country right join state on country.code=state.country_code


Thinking Machines – Java DB Page 7

Java code to perform CRUD Operations

While Staying in c:\javadb folder create the following insert1.java file


insert1.java
import java.sql.*;
class insert1
{
public static void main(String gg[])
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection c=DriverManager.getConnection("jdbc:derby://localhost:1527/db/tmplacements");
Statement s=c.createStatement();
s.executeUpdate("insert into city (name,state_code) values('Shujalpur',2)");
s.close();
c.close();
System.out.println("Record inserted");
}catch(SQLException sqlException)
{
System.out.println(sqlException);
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe);
}
}
}

compile the above code using javac

to run type
java -classpath c:\java-derby\lib\derbyclient.jar;. Insert1

You should see the message Record Insert, if this message doesn't appear, it means that either you have
made a mistake while typing the name in class.forName, or some mistake in
DriverManager.getConnection or some mistake in insert SQL Statement.

If record inserted appears, then connect to ApacheDerby using the client tool (ij) and check if the
record got inserted or not by firing the (select * from city) SQL Statement.

For the rest of the examples, use the same classpath for execution

insert2.java
import java.sql.*;
class insert2
{
Thinking Machines – Java DB Page 8

public static void main(String data[])


{
try
{
String name=data[0];
int stateCode=Integer.parseInt(data[1]);
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection c=DriverManager.getConnection("jdbc:derby://localhost:1527/db/tmplacements");
Statement s=c.createStatement();
String sql="insert into city (name,state_code) values('"+name+"',"+stateCode+")";
System.out.printf("The following SQL Statement will be fired\n[%s]\n",sql);
s.executeUpdate(sql);
s.close();
c.close();
System.out.println("Record inserted");
}catch(SQLException sqlException)
{
System.out.println(sqlException);
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe);
}
}
}

For execution use the same classpath as done earlier, but don't forget to pass command line arguments
representing the name of the city and state code.
What I did is as follows

java -classpath c:\java-derby\lib\derbyclient.jar;. insert2 Sehore 2

Now I won't be telling you that how you should execute the code. Understand it on your own by
looking at the code.

Insert3.java
import java.sql.*;
class insert3
{
public static void main(String data[])
{
try
{
String name=data[0];
int stateCode=Integer.parseInt(data[1]);
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection c=DriverManager.getConnection("jdbc:derby://localhost:1527/db/tmplacements");
Thinking Machines – Java DB Page 9

PreparedStatement ps=c.prepareStatement("insert into city (name,state_code) values(?,?)");


ps.setString(1,name);
ps.setInt(2,stateCode);
ps.executeUpdate();
ps.close();
c.close();
System.out.println("Record inserted");
}catch(SQLException sqlException)
{
System.out.println(sqlException);
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe);
}
}
}

insert4.java
import java.sql.*;
class insert4
{
public static void main(String data[])
{
try
{
String name=data[0];
int stateCode=Integer.parseInt(data[1]);
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection c=DriverManager.getConnection("jdbc:derby://localhost:1527/db/tmplacements");
PreparedStatement ps=c.prepareStatement("insert into city (name,state_code)
values(?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1,name);
ps.setInt(2,stateCode);
ps.executeUpdate();
ResultSet r=ps.getGeneratedKeys();
if(r.next())
{
int code=r.getInt(1);
System.out.println("Code alloted : "+code);
}
r.close();
ps.close();
c.close();
System.out.println("Record inserted");
}catch(SQLException sqlException)
{
Thinking Machines – Java DB Page 10

System.out.println(sqlException);
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe);
}
}
}

select1.java
import java.sql.*;
class select1
{
public static void main(String gg[])
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection c=DriverManager.getConnection("jdbc:derby://localhost:1527/db/tmplacements");
Statement s=c.createStatement();
ResultSet r;
int code;
String name;
r=s.executeQuery("select * from country");
while(r.next())
{
code=r.getInt("code");
name=r.getString("name").trim();
System.out.printf("Code : %10d, Country : %-30s\n",code,name);
}
r.close();
s.close();
c.close();
}catch(SQLException sqlException)
{
System.out.println(sqlException);
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe);
}
}
}
Assignement :
Try to retrieve records using joins
create update1.java, update2.java and update3.java
create delete1.java, delete2.java and delete3.java
Thinking Machines – Java DB Page 11

Change insert1,insert2 to accommodate the logic to retrieve the generated code

You might also like