UNIT - 5 Final
UNIT - 5 Final
UNIT-5
1. Introduction
• Strings are treated differently in Java compared to C language;
• In the latter case, it represents an array of characters terminated by null
character.
• In Java, a string is an object of a class, and there is no automatic
appending of null character by the system.
• In Java, there are three classes that can create strings and process them with
nearly similar methods.
(i) class String
(ii) class StringBuffer
(iii) class StringBuilder
• All the three classes are part of java.lang package.
• All the three classes have several constructors that can be used for
constructing strings.
• In the case of String class, an object may be created as
String str1 = "abcd";
Here :
o String is a Predefined class of java.lang package
o Str1 is an object not a variable.
o "abcd" is string literal
Storage of Strings
• The memory allocated to a Java program is divided into two segments:
(i) Stack
(ii) Heap
• The objects of class String have a special storage facility, which is not
Output:
C:\>javac StringTest.java
C:\>java StringTest
Are reference of strx and stry same? true
Are reference of strx and strz same? false
Are reference of str1 and strz same? false
Are reference of s1 and s2 same? false
Are strings in strx and strz equal? true
Immutability
i. String class
• The string objects created by class String are immutable.
• By immutable implies that once an object is created, its value or contents cannot be
changed.
• Neither the characters in the String object once created nor their case (upper or lower)
can bechanged.
• New String objects can always be created and assigned to older String object references.
• Thus, when you change the content of a string by defining a new string, the old and
newremain in the memory.
• The immutable objects are thread safe and so are the String objects.
2. Interface CharSequence
It is an interface in java.lang package.
It is implemented by several classes including the classesString, StringBuffer,
and StringBuilder.
Example: CharSq.java
public class CharSeq
{
public static void main(String args[])
{
CharSequence csq1 = "ABCD";
System.out.println("Second letter in csq1 ="+csq1.charAt(1));
System.out.println("Length of csq1 = " + csq1.length());
C:\>javac CharSeq.java
C:\>java CharSeq
Second letter in csq1 = B
Length of csq1 = 4
The csq3 = Amrit
The csq2 = XYZ12345
The sub sequence(2,6) of csq2 sq = Z123
3. Class String
• The class String is used to represent strings in Java. It is declared as
public final class String extends Object implements serializable,
comparable<String>, charSequence
Output:
C:\>javac StringArray.java
C:\>java StringArray
str2 =ABCDE
Output:
C:\>javac StringUnicode.java
C:\>java StringUnicode
str =ABC
Example: StringArray2.java
public class StringArray2
{
public static void main(String args[]) throws Exception
{
byte []bray = new byte[]{65, 66, 67, 68, 69};
String str = new String(bray,1,3,"ascii");
Output:
C:\>javac StringArray2.java
C:\>java StringArray2
str =BCD
Example: StringUnicode2.java
C:\>java StringUnicode2
str =ABC
• Thus, in String ‘Delhi’ the index value of ‘D’ is 0, index value of ‘e’
is 1, ‘h’ is 3, and so on.
2. void getChars (int SourceStartindex, int SourceEndindex,
char targetarray[], int targetindexstart)
• This method takes characters from a string and deposits them in another string.
• int SourceStartindex and int SourceEndindex relate to the source string.
• char targetarray[] relates to the array that receives the string characters. The
int targetindexstart is the index value of target array.
Example: MethodsChar.java
public class MethodsChar
{
public static void main(String args[])
{
String str1 = "Delhi"; String str2 = "Vijayawada";
String str = "I am going to Delhi and from there to Mumbai";
C:\>java MethodsChar
Length of string str1 =5
Fourth Character in Delhi = h
Fifth Character in Vijayawada = y
aSTR = Delhi
Output:
C:\>javac MethodCompare.java
C:\>java MethodCompare
str2.compareTo(str1) =25
str1.compareTo(str2) =-25
str3.compareTo(str1) =0
Output:
C:\>javac StringMethods.java
C:\>java StringMethods
str3 = AA
str2.equals(str1) =false
str1.equals(str2) =false
str3.equals(str1) =true
Length of str2 =2
Output:
C:\ >javac ModifyString.java
Example: StringSearch.java
public class SearchString
{
public static void main (String args[])
{
Output:
C:\>java SearchString
The index of "e" in the String str1 is at index = 1
The last index of "e" in str1 is at index = 18
The last occurrence "of" in String str2 is at index = 21
The occurrence of "e" after index 8 in str1 = 10
The index of last occurrence of "n" = 9
Example: StringValue.java
C:\>javac StringValue.java
C:\>java StringValue
s2.valueOf(n) = 70
s2.valueOf(l) = 25674
s3 = 45.76
s2.valueOf(array) = De1hi
s1.toString() = Railways
Example1: StringBufferDemo.java
class StringBufferDemo
{
public static void main (String args[])
{
StringBuffer bufStr = new StringBuffer ("Hello World Example");
System.out.println("bufStr = " + bufStr);
bufStr.setLength(11);
char ch=bufStr.charAt(4);
System.out.println("Character at 4th position = " + ch);
bufStr.setCharAt(7, 'e');
System.out.println(" Now New bufStr =" + bufStr);
}
}
Output:
C:\>javac StringBufferDemo.java
C:\>java StringBufferDemo
bufStr = Hello World Example
Length of bufStr =19
New Length of bufStr = 11
Capacity of bufStr =35 New
bufStr =Hello World
Character at 4th position = o
Now New bufStr =Hello Werld
Example2: StringBufferDemo2.java
class StringBufferDemo2
{
public static void main (String args[])
{
StringBuffer bufStr = new StringBuffer ("Hello World");
System.out.println("bufStr =" + bufStr);
bufStr.reverse();
System.out.println("After reversing bufStr =" + bufStr);
str.delete (11,16);
System.out.println("After deletion str = " + str);
str.deleteCharAt(21);
System.out.println("After delete dot, str = " + str);
Output:
C:\>javac StringBufferDemo2.java
C:\>java StringBufferDemo2
bufStr =Hello World
After reversing bufStr =dlroW olleH
Before insert, str = Delhi is a city.
After insert, str = Delhi is a very big city.
After deletion str = Delhi is a big city.
After replace str = Delhi is a big market.
After delete dot, str = Delhi is a big market
After append str = Delhi is a big market of electronic goods.
Example: StringBuildDemo.java
Output:
C:\>javac StringBuildDemo.java
C:\>java StringBuildDemo
Before append, builder1 = Delhi
After append, builder1 = Delhi-110024
The length of builder2 = 0
The capacity of builder2 = 16
Before append, builder2 =
After append, builder2 = New Delhi
Example: StringBuildDemo2.java
import java.lang.StringBuilder;
builder1.deleteCharAt(8).delete(7,8);
System.out.println("The new string after delete = " + builder1);
C:\>javac StringBuildDemo2.java
C:\>java StringBuildDemo2
The new string after delete = Java is object oriented programming language
• Some computer programs may be divided into segments that can run independent of
each other or with minimal interaction between them.
• Each segment may be considered as an independent path of execution called athread.
• If the computer has multiple processors, the threads may run concurrently on different
processor thus saving computing time.
• Threads are useful even if the computer has a single-core processor.
• The different processes in a computer take different times.
• A CPU may have two cores - dual core or four cores - quad, six cores, or more.
• CPUs having as many as 50 cores have also been developed.
• Moreover, computers with multi-core CPU are affordable and have become part of
common man's desktop computer.
• Advancements in hardware are forcing the development of suitable software for optimal
utilization of the processor capacity. Multithread processing is the solution.
• Multithread programming is inbuilt in Java and CPU capacity utilization may be
improved by having multiple threads that concurrently execute different parts of a
program.
A. How Single Processor – tasks carried out in Single Sequence is illustrated in the
following diagram.
B. The following diagram shows the Single processor – threads share the time of processor.
C. The following diagram shows the multi-core processor – threads execute concurrently.
3. Thread Class
• In Java, threads are based on the class Thread belonging to java.lang package, that
is,java.lang.Thread.
• A thread is an object of class Thread and can invoke the instance methods defined in
theclass.
• Even if a thread is not explicitly defined, one thread is automatically created by
thesystem for the execution of the main method. It is generally called main
Thread.
• A thread does not start working on birth. It has to invoke the start() method that gives
itthe life, otherwise it is a lifeless thread object.
• After getting life, a thread executes a code of instructions (target) as specified by the
userin the overloaded method run().
The Thread class has defined several constructors.
i. Thread(): It allocates a new thread object as thread(null, null, generatedname). Every
thread must have a name.
ii. Thread(String threadname): It allocates a thread with name specified by theuser. It is
of the form thread(nall null, name). A thread may be created as
Thread t2 new Thread("MyThread");
iii. Thread(Runnable object) : The constructor allocates a thread with a specified target.The
name by the compiler as Thread-0, Thread-1, and so on.
iv. Thread (Runnable object, String threadName): Thread is allocated with a specified
target and user specified name threadnume.
v. Thread (ThreadGroupgroup, Runnable object): It allocates thread with specifiedgroup
and target.
vi. Thread (ThreadGroupgroup, Runnable object, String Threadname): The constructor
allocates thread with specified thread group, target, and thread name.
Example: ThreadX.java
public class ThreadX extends Thread
{
public void run()
{
System.out.println("It is Threadx class");
}
Output:
Thread Group
• Every thread is in fact a member of a thread group. The thread groups are useful for
invoking methods that apply to all the threads.
• The thread is made a member of a group at the time of its creation with constructor.
• The thread remains the member of the designated group throughout its life.
• It cannot become the member of another group.
• If a thread's group is not specified in its constructor, as is the usual case, the thread isentered
into the same group as the thread that created it.
• The default thread group for a newly executing Java application is the main group.
• When a thread dies, its thread group becomes null
The following methods of class Thread have been deprecated because these are either unsafe
or are deadlock pruned.
stop() : The invoking thread stops executing with clean-up, and thus, exposes sensitive
resources to other threads.
destroy(): It terminates the thread without clean-up. Deadlock pruned method.
suspend(): It temporarily suspends the execution of thread without clean-up. Deadlock
pruned method
resume(): It brings back the suspended thread to runnable state. Used only after suspend().
countStackFrames(): It is not well-defined. Returns number of stack frames in this thread.
Example: ThreadNew3.java
int n = 10;
System.out.println("Square root of " + n + " = " +Math.sqrt(n));
System.out.println("The active count = "+ this.activeCount());
4. Main Thread
• When we run a program in Java, one thread is automatically created and it executes the
main method. The thread is called main thread. This is the thread from which other threads
are created.
• The threads created from the main thread are called child threads.
• A program keeps running as long as the user threads are running.
• The main thread also has the status of a user thread.
• The child threads spawned from the main thread also have the status of user thread.
• Therefore, main thread should be the last thread to finish so that the program finisheswhen
the main method finishes.
• A thread is controlled through its reference like any other object in Java.
• The main thread can also be controlled by methods of Thread class through its reference
that can be obtained by using the static method current Thread(). Its signature is
Thread thread = Thread.currentThread();
• sleep() method suspend the execution for the given specified time interval. Ex:
thread.sleep(500);
the above statement will suspend the execution of main() method for 500 ms, which is the
argument of the method.
• setName() method add the new name to the existing threadEx:
thread.setName("My Thread")
Example: MyThread.java
class MyThread
{
public static void main (String args[])
{
Thread thread = Thread.currentThread(); //Thread reference
System.out.println("CurrentThread :" + thread);
Output:
C:\>javac MyThread.java
C:\>java MyThread
CurrentThread :Thread[main,5,main]
Before modification ,Thread Name =main
Change the name to MyThread.
After modification ,Thread Name =MyThread
Is the thread alive? True
Thread[MyThread,5,main] i = 0
Is the thread alive? true
Thread[MyThread,5,main] i = 1
Example: MyClass.java
Output:
C:\>javac MyClass.java
C:\>java MyClass
It is MyThread.
Example: MyThreadClass.java
Output
{
//Method reference
Output:
C:\>javac ThreadMethods.java
C:\>java ThreadMethods
It method reference thread.
It is Lambda expression method thread.
It is conventional method thread.
6. Thread States
Thread states are as follows.
i. New thread state
ii. Ready-to-run state
iii. Running state
iv. Non-runnable state-waiting, sleeping, or blocked state
v. Dead state
The transition from one state to another is shown in the figure. The different states are as
follows
1. New thread state. The thread is just created. It is simply a lifeless object of class Thread.
2. Runnable state: When the thread invokes the method start(), it becomes alive. This state
iscalled runnable state. It is not a running state. It is simply a ready-to-run. The thread has
to wait till it is scheduled, that is, selected from the group of threads waiting in running
state for dispatch to the CPU by the scheduler
3. Running state. If the scheduler chooses the thread from the waiting list of threads and
dispatches it CPU, the thread transits to runnable state, that is, it starts executing the method
run() meant for it. This is turning state. If it completes its run() method successfully, its life
span is over. The thread is automatically terminated and it goes to dead state from which
it cannot be revived.
4. Sleep state: The code that a thread is executing may require it to relinquish the CPU for
sometime so the other threads can possess CPU. The sleep method may be invoked by the
thread. The time period of them is the argument of sleep() method. It is either long
milliseconds or int nanoseconds. After the sleep the thread returns normally to runnable
state.
5. Blocked state. A running thread gets into blocked state if it attempts to execute a task.
6. State wait: A thread gets into wait state on invocation of any of the three methods wait()
or wait (long millisees) or wait (long millisecs, int nanosecs).
7. yield. The use of code Thread yield(), is another method besides the sleep for the thread
tocease the use of CPU. The thread transits to Runnable state.
8. Suspended. The term belongs to legacy code and is defined in Java 1.1. The suspended
thread can be brought back to normal Runnable state only by method resume(). Both the
A UDAYA KUMAR, GVPCEW
32
methods suspend() and resume() are now deprecated, instead one should use wait()and notify().
thread2.start();
try
{
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 when it has finished it's execution - "+ thread2.getState());
}
}
/*
OUTPUT
*/
7. Thread Priority
Thread priority is an important factor among others that helps the scheduler to decide which thread to
dispatch the CPU from the group of waiting threads in their runnable state.
All the threads have a priority rating of be When several threads are present, the priority value
determines which thread has the chance to possess the Offset.
The actual allocation is done by the scheduler. Thus, a thread with higher priority has higher
chance getting the CPU and also a higher share of CPU time. Keeping equal priority for all threads
ensures that each has equal chance to share CPU time, and thus, no thread starves, because when
a thread with higher priority enters the Runnable state, the operating system may pre-empt the
scheduling by allocating CPU to the thread with higher priority.
When this thread returns from sleep or wait state, the same story may be repeated. When several
threads of different priorities are present, it is quite likely that a thread with the lowestpriority
may not get a chance to possess CPU. This is called starvation.
Example: ThreadPriority2.java
PT1.threadStart();
PT2.threadStart();
PT3.threadStart();
try
{
Thread.sleep(50);
} catch(InterruptedException e)
{
System.out.println("Main thread sleep interrupted");
}
}
}
Output:
C:\>javac ThreadPriority2.java
C:\>java ThreadPriority2
Particulars of new thread:Thread[First,10,main]
Particulars of new thread:Thread[Second,5,main]
Particulars of new thread:Thread[Third,1,main]
Priority of new thread: 10
Priority of new thread: 5
Priority of new thread: 1
8. Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared
resource. Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
In several multithreaded programs, the different threads are required to access the same resource,
for example, a memory object during the execution. One thread may attempt toupdate it, while
the other wants to read it and a third may try to alter the content of the memory.
Such a situation may give rise to race condition and the result may be quite different if the
sequence of operations actually followed is different from the desired one.
Proper execution requires that at any point of time, only one thread be allowed to use thecritical
resource till it finishes its task.
We are all aware of the computerized banking system. In one branch, money may be deposited
in your account, while you are withdrawing money at another branch. There can bea problem if
one thread has partly finished its task, while the other gets in. It will corrupt the data.
Synchronization solves this problem by allowing only one thread can access the resource. The
second thread should be allowed only when the first has finished its task.
Example: SyncDemo.java
class Counter
{
int count=0;
public void increment()
{
count++;
}
}
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
Output:
C:\>javac SyncDemo.java
C:\>java SyncDemo
Count = 8343
C:\>java SyncDemo
Count = 9998
C:\>java SyncDemo
Count = 9865
C:\>java SyncDemo
Count = 9989
C:\>java SyncDemo
Count = 9790
C:\>java SyncDemo
Count = 9954
C:\>java SyncDemo
Count = 9799
Here the count should be 10000, but it is printing less than 10000. To solve thisproblem,
add synchronized keyword to the increment() method as shown in the following code.
class Counter
{
int count=0;
public synchronized void increment()
{
count++;
}
}
C:\>javac SyncDemo.java
C:\>java SyncDemo
Count = 10000
C:\>java SyncDemo
Count = 10000
C:\>java SyncDemo
Count = 10000
In a multithreaded program, the race and deadlock conditions are common when improperly
synchronized threads have a shared data source as their target.
A race condition may occur when more than one thread tries to execute the code
concurrently. A thread partly does the job when the second thread enters.
If the process is atomic, that is, it cannot be subdivided the effect of race condition will belimited.
However, when the process is not atomic and can be subdivided into two or more sub- processes,
it may occur that a thread has done subprocess, and the second thread enters andstarts executing.
In such cases, the results can be far from the desired ones.
Therefore, a race condition is a situation in which two or more threads try to execute code and
their actions get interleaved. The solution for such condition is the synchronization, and therefore,
only one thread should enter code at a time and othersshould wait until the first hasdone its job.
A deadlock condition may lead to program crash. Such a situation occurs when two threads are
attempting to carry out synchronized hods that are inter-dependent, that is, the completion of
Method1 needs Method2 and completion of Method2 needs Method1.
10.Inter-thread Communication
• Inter-thread communication involves synchronized threads to communicate with each other to pass
information. In this mechanism, one of the threads is paused in its critical section to run and another
thread is allowed to enter in the same critical section to be executed
• The inter-communication between threads is carried out by three methods, wait(), notify(), and
notifyAll(), which can be called within the synchronized context.
Example: ThreadDemo2.java
class BankAccount
{
int accountNumber; static double balance;
BankAccount(int n, double y)
{
accountNumber = n;
balance = y;
}
new Thread()
{
public void run()
{
ba.deposit(15000);
}
}.start();
}
}
• These direct methods are very convenient to control the operation of threads in a multithread
environment.
• However, in some situations, they may crash the program or cause serious damage to critical data.
• For example, if a thread has got the lock to a critical synchronized section of code and gets
suspended, it will not release the lock for which other threads may be waiting.
• Instead of methods suspend() and resume(), the methods wait() and notify() are used.
Example: SRS.java
System.out.println("Thread Interrupted");
}
}
synchronized void my_suspend()
{
suspend_flag=true;
}
synchronized void my_resume()
{
suspend_flag=false;
notify();
}
synchronized void my_stop()
{
suspend_flag=false;
stop_flag=true;
notify();
}
}
public class SRS
{
public static void main(String args[])
{
try
{
temp t1=new temp("SRS");
System.out.println("Thread SRS is Created and Started");
Thread.sleep(2000);
t1.my_suspend();
System.out.println("Thread SRS is Suspended");
Thread.sleep(2000);
t1.my_resume();
System.out.println("Thread SRS is Resumed");
Thread.sleep(2000);
t1.my_suspend();
System.out.println("Thread SRS is Suspended");
Thread.sleep(2000);
t1.my_resume();
System.out.println("Thread SRS is Resumed");
Thread.sleep(2000);
t1.my_stop();
System.out.println("Thread SRS is Stopped");
}
catch(InterruptedException IE)
{
System.out.println("Generated interrupted exception");
}
}
}
/*
OUTPUT
Thread SRS is Created and Started
Thread SRS is Suspended
Thread SRS is Resumed
Thread SRS is Suspended
Thread SRS is Resumed
Thread SRS is Stopped
*/
• JDBC stands for Java Database Connectivity and has been developed by Sun Microsystems.
• It is a standard Java API that defines how the front-end application (that may be web
application or simple Java application) may access the database.
• It provides a standard library for accessing a wide variety of database systems. Previously,
Open Database Connectivity (ODBC) API used to be the database API for connecting and
executing query with the database.
• JDBC applications are platform independent, and thus, they can be used for connecting with
Internet applications. JDBC applications are simpler and easier to develop.
• JDBC API and JDBC driver form the important components in order to fetch/store the
information to the database.
• JDBC API is installed at the client side. Therefore, when the user wants to fetch some data
from the database, the user sets up the connection to JDBC manager using JDBC API through
the Java application.
• JDBC manager needs a medium in order to communicate with the database. JDBC driver
provides this medium and the required information to JDBC manager, JDBC library includes
APIs that define interfaces and classes for writing database applications in Java.
• Through the JDBC API, we can access a wide variety of database systems including
relational as well as non-relational database system. This chapter focuses on using JDBC to
access data in Relational Database.
• Relational Database Management System (RDBMS). It is a database system that is based
on relational model. Data in RDBMS is stored in the form of database objects called tables.
• Table is a collection of related data entries and consists of columns and rows.
• Some of the most widely used relational database systems include Microsoft MySQL server,
Oracle, and IBM's DB2.
• Any Java-based application can access a relational database. For this, any RDBM system
needs to be installed that provides driver conforming to Java Database Connectivity.
• JDBC API enables the programmers to change the underlying DBMS (for example, from
MySQL to Oracle), without changing the Java code that accesses the database.
2. JDBC Architecture
• In this model, Java application communicates directly with the database. For this, JDBC
driver is required and it can establish direct communication with the database.
• As can be seen from the figure, both Java application and JDBC API are located at the
clientmachine and the DBMS and database are located at the database server.
• User sends commands to the database. The commands processed and the results of these
statements are sent to the user.
• Java application and the database may reside on the same machine. Alternatively, database
may be on the server machine, while the Java application may be on the client machine,
which may be connected via the network.
• Middle tier has often been written in languages such as C or C++ that provide the fast
performance.
• However, Java platform has become the standard platform for middle-tier development
withthe advancements made in the optimizing compilers. These compilers translate Java
byte code into an efficient machine specific code.
• This model is usually common in web applications in which the client tier is implemented
in the web browser. Web server forms the middle tier and the database management
system runson database server. This model provides better performance and simplifies the
deployment ofapplications.
• MySQL is the most widely used open-source relational database management system.
• It is considered to be one of the best RDBMS systems for developing web-basedsoftware
applications as it provides speed, flexi bility, and reliability.
• Before we can use MySQL with JDBC, we first need to install MySQL.
• “MySQL community edition” freely available and can be downloaded from the MySQL
website
http://www.mysql.com .
Steps to install MySQL database system on Windows platform are as follows:
i. On successful download, click the mySQL icon. MySQL Server 5.6 setup. Click on
theNext button.
ii. License agreement page would appear next. Read the terms and conditions and click
on Iaccept the wizard window would terms in the license Agreement checkbox.
iii. Next, it will ask for the set-up type that suits your needs. Click on Typical button in
Choose set up Type screen.
iv. Then click on install button for starting the installation process wizard.
v. Completed MySQL Server 5.6 Setup Wizard would appear. Click on finish to exit the
MySQL Server Instance Configuration screen would appear, and select the Detailed
Configuration.
vi. Following this, MySQL Server Instance Configuration Wizard would open up and
choose the server as Developer Machine.
vii. Now click on Next button, and select the Dedicated MySQL Server Machine or you
may choose Developer Machine if other applications and tools are being run on your
system.
viii. Thereafter, select multifunctional database for general purpose database, when
MySQLServer Instance Configuration Wizard screen appears. Then, select the drive
where the database files would be stored.
ix. Keep the default port as 3306 and specify the root password.
After the successful installation of MySQL, we need to install MySQL Connector/J (where
J stands for Java). This is the JDBC driver that allows Java applications to interact with
MySQL.
dev.mysql.com/downloads/connector/j/3,1.html.
SQL Statements
SQL statements are used for performing various actions on the database.
i. SQL select statements:
The select statements are used to select data from the database.
Syntax :
select column_name1, column_name2 from tablename;
Example-1:
select id, stdName from Student;
Here :
id and stdName are the column names
Example-2:
Select * from Student;
The above statement selects all the columns from Student table.
For instance,
example:
delete from Student where firstname="Riya";
A UDAYA KUMAR, GVPCEW
48
This section focuses on how to set up the connection to MySQL database from NetBeans IDE.
NetBeans IDE supports MySQL RDBMS. In order to access MySQL database server inNetBeans
IDE, we have to first configure the MySQL Server properties. This involves the following steps:
1. Open the NetBeans IDE, right click the database node in the services window. Select
Register MySQL Server MySQL server properties dialog box would open. Confirm that
theserver host name and port are correct. The default server host name is localhost and
3306 isthe default server port name.
2. Enter the administrator password. You can give any password and default is set to blank
password.
3. At the top of dialog box, click on the Admin properties tab. Here, you can enter the
information for controlling the MySQL server.
4. In the admin properties dialog box, enter the path/URL to admin tool. This is the location
of MySQL Administration.
5. Next, you have to enter the path to start the command. For this, look for mysqld in the bin
folder MySQL installation directory of
6. In the path to stop the command field, type or browse to the location of MySQL stop
command. This is the path where mysqladmin the bin folder of MySQL installation
directoryis located.
Additional steps that must be checked before starting with the involvement of Java-based
database connectivity:
1. Before starting, make sure that MySQL Database server is running. If database server is
not connected, it will show 'disconnected'. For connecting it, right click the Database, and
choose 'connect". This may also prompt to give password to connect to the database server
2. When a new project is created in NetBeans, copy the mysql-connector/java JAR file into
the library folder.
Fig. 27.1 depicts the JDBC connectivity model. JDBC API enables Java applications to be
connected to relational databases through standard API. This makes possible for the user to
A UDAYA KUMAR, GVPCEW
49
establish a connection to a database, create SQL or MySQL statements, execute queries in the
database, and so on. JDBC API comprises the following interfaces and classes:
Driver manager
This class manages a list of database drivers. It matches the connection request from the Java
application with the database driver using communication sub-protocol. It acts as an interface
between the user and the driver and is used to get a Connection object.
Commonly used methods of this class are as follows
Method
Driver
• It handles communication with the database server. JDBC drivers are written in Java
language in order to connect with the database. JDBC driver is a software component
comprising a set of Java classes that provides linkage between Java program running on
Javaplatform and RDBM system that is residing on the operating system.
• There are basically four different types of JDBC drivers and these implementations
varybecause of the wide variety of operating systems and hardware platforms available in
which Java operates
• Type 1 JDBC driver provides a standard API for accessing SQL on Windows platform.
In this type of the driver, JDBC bridge is used to access ODBC drivers installed on the
client machine. For using ODBC, Data Source Name (DSN) on the client machine is
required to beconfigured.
• The driver converts JDBC interface calls into ODBC calls. It is, therefore, the least
efficientdriver of the four types. These drivers were mostly used in the beginning and now
it is usually used for experimental purposes when no other alternative is available.
• In Type 2 driver, Java interface for vendor-specific API is provided and it is implemented
innative code. It includes a set of Java classes that make use of Java Native Interface
(JNI) and acts as bridge between Java and the native code.
• JNI is a standard programming interface that enables Java code running in a Java Virtual
Machine (JVM) to call and be called by native applications (these include the programs
thatare specific to a particular hardware and operating system like C/C++).
• Thus, the driver converts JDBC method calls into native calls of the database API. For
usingthis driver, it is required that RDBMS system must reside in the same host as the
client program.
• The Type 2 driver provides more functionality and performance than Type 1 driver. For
usingthis driver in a distributed environment, it is required that all the classes that operate
on the database should reside on the database host system.
• It is similar to Type 2 driver but in this case, the user accesses the database through
TCP/IP connection. The driver sends JDBC interface calls to an inter mediate server,
which then connects to the database on behalf of the JDBC driver.
• Type 3 and 4 drivers are preferably used if the program application does not exist on the
same host as the database. It requires data base-specific coding to be done in the middle
tier.
• Type 4 JDBC driver is completely written in Java, and thus, it is platform independent.
The driver converts JDBC calls directly into vendor-specific database protocol.
• It is installed inside the Java Virtual Machine of the client and most of the JDBC drivers
are of Type 4.
• It provides better performance when compared to Type 1 and 2 drivers as it does not have
the overhead of conversion of calls into ODBC or database API calls, However, at the
client side, a separate driver is required for each database.
Packages:
There are two packages that make up the JDBC API.
They are
i. java.sql
ii. javax.sql
1. java. sql package provides API for accessing and processing data that is stored in a data
source. This API comprises framework whereby different drivers can be installed
dynamically in order to access different data sources. For instance, it comprises API for
establishing a connection with a database via the Driver manager facility, sending SQL
statements a database, retrieving and updating the results of the query, and so on.
2. javax.sql package provides the required API for server-side data source access and
processing. This package supplements the java.sql package. It is included in the Java
Platform Standard Edition (Java SETM).
Connection:
This interface comprises methods for making a connection with the database. All types of
communication with the database is carried out through the connection object only.
Statement
Object created from this interface is used to submit the SQL statements to the database.
ResultSet
It acts as an iterator that enables to move through the data. Object created from interface isused
to data received from the database after executing SQL query.
SQL Exception
This class handles errors that may occur in a database application.
• Class.forName() : Here we load the driver’s class file into memory at the runtime. No need
of using new or creation of object .The following example uses Class.forName() to load the
Oracle driver –
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2. Creating a Connection
After loading the driver, establish connections using :
Connection con = DriverManager.getConnection(url,user,password)
user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.
con: is a reference to Connection interface.
url : Uniform Resource Locator.
Where oracle is the database used, thin is the driver used , @localhost is the IP Address where database
is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String
type and are to be declared by programmer before calling the function. Use of this can be referred
from final code.
3. Create a statement
Once a connection is established you can interact with the database. The Statement, CallableStatement,
and PreparedStatement interfaces define the methods that enable you to send SQL commands and
receive data from your database. Use of Statement is as follows:
Statement st = con.createStatement();
Implementation
Now that we understood all the steps involved, let us implement them programmatically. The below
code inserts data into oracle database.
Note: Make sure oracle ojdbc6.jar file is in classpath.
DatabaseExample.java
import java.sql.*;
import java.util.*;
class Test
{
public static void main(String a[]) throws SQLException
{
//Creating the connection
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";
Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("Data inserted successfully");
else
System.out.println("insertion failed");
}
catch(Exception ex)
{
System.out.println("insertion failed");
System.out.println(ex);
}
finally
{
6. ResultSet Interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method
as well as we can make this object as updatable by:
10) public String getString(String is used to return the data of specified column
columnName): name of the current row as String.
import java.sql.*;
class FetchRecord
{
public static void main(String args[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:xe","system","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultS
et.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
Example
create database empdb;
use empdb;
create table tblemployee (empid integer primary key, firstname varchar(32), lastname varchar(32),
dob date);
the console. Please make sure you have the MySQL JDBC driver in the project classpath.
package com.journaldev.examples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
/**
* Java Resultset Example of Retrieving records.
*/
Output:
empId:1
firstName:Mike
lastName:Davis
dob:1998-11-11
empId:2
firstName:Josh
lastName:Martin
dob:1988-10-22
empId:3
firstName:Ricky
lastName:Smith
dob:1999-05-11
7. Transaction Management in JDBC
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
fast performance It makes the performance fast because database is hit at the time of commit.
Method Description
import java.sql.*;
class FetchRecords
{
public static void main(String args[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}
}
If you see the table emp400, you will see that 2 records has been added.
import java.sql.*;
import java.io.*;
class TM
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system","oracle");
con.setAutoCommit(false);
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);
ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit"))
{
con.commit();
}
if(answer.equals("rollback"))
{
con.rollback();
}
}
con.commit();
System.out.println("record successfully saved");
It will ask to add more records until you press n. If you press n, transaction is committed.
HTML Tutorial
Method Description
void clearBatch() The method removes all the statements that one has
added using the addBatch() method.
FileName: FetchRecords.java
import java.sql.*;
class FetchRecords
{
public static void main(String args[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into user420 values(190,'abhi',40000)");
stmt.addBatch("insert into user420 values(191,'umesh',50000)");
stmt.executeBatch();//executing the batch
con.commit();
con.close();
}
}
If you see the table user420, two records have been added.
import java.sql.*;
import java.io.*;
class BP
{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
while(true)
{
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);
ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.addBatch();
}
}
Output:
enter id
101
enter name
Manoj Kumar
enter salary
10000
Want to add more records y/n
y
enter id
101
enter name
Harish Singh
enter salary
15000
Want to add more records y/n
y
enter id
103
enter name
Rohit Anuragi
enter salary
30000
Want to add more records y/n
y
enter id
104
enter name
Amrit Gautam
enter salary
40000
Want to add more records y/n
n
record successfully saved
It will add the queries into the batch until user press n. Finally, it executes the batch. Thus, all
the added queries will be fired.