VND Openxmlformats-Officedocument Wordprocessingml Document&rendition 1-1
VND Openxmlformats-Officedocument Wordprocessingml Document&rendition 1-1
n Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
By new keyword
StringExample.java
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
The java.lang.String class provides many useful methods to perform operations on sequence
of char values.
No Method Description
.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
The Java String class charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string. It
returns StringIndexOutOfBoundsException, if the given index number is greater than or
equal to this string length or a negative number.
Syntax
The String class equals() method compares the original content of the string. It compares
values of string for equality. String class provides the following two methods:
o public boolean equals(Object another) compares this string to the specified object.
o public booleanequalsIgnoreCase(String another) compares this string to another
string, ignoring case.
Teststringcomparison1.java
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
Methods for searching strings
Java String indexOf()
The Java String class indexOf() method returns the position of the first occurrence of the
specified character or string in a specified string.
There are four overloaded indexOf() method in Java. The signature of indexOf() methods are
given below:
1 int indexOf(int ch) It returns the index position for the given char value
2 int indexOf(int ch, int fromIndex) It returns the index position for the given char value
and from index
3 int indexOf(String substring) It returns the index position for the given substring
4 int indexOf(String substring, int It returns the index position for the given substring
fromIndex) and from index
Parameters
fromIndex: The index position from where the index of the char value or substring is
returned.
Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
public append(String s) It is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.
public insert(int offset, String s) It is used to insert the specified string with this string at
synchronized the specified position. The insert() method is overloaded
StringBuffer like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public replace(int startIndex, It is used to replace the string from specified startIndex
synchronized int endIndex, String str) and endIndex.
StringBuffer
public delete(int startIndex, int It is used to delete the string from specified startIndex
synchronized endIndex) and endIndex.
StringBuffer
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total
number of characters.
public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int beginIndex, It is used to return the substring from the specified
int endIndex) beginIndex and endIndex
The append() method concatenates the given argument with this String.
StringBufferExample.java
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
Output:
HJavaello
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.
StringBufferExample4.java
1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK 1.5.
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public StringBuilder replace(int It is used to replace the string from specified startIndex and
startIndex, int endIndex, String endIndex.
str)
public StringBuilder delete(int It is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number of
characters.
public String substring(int It is used to return the substring from the specified beginIndex.
beginIndex)
public String substring(int It is used to return the substring from the specified beginIndex
beginIndex, int endIndex) and endIndex.
The StringBuilder append() method concatenates the given argument with this String.
StringBuilderExample.java
1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Multithreaded Programming
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We
create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.
// Main Class
publicclassMultithread {
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti = 0; i< n; i++) {
MultithreadingDemo object
= newMultithreadingDemo();
object.start();
}
}
}
// Main Class
classMultithread {
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti = 0; i< n; i++) {
Thread object
= newThread(newMultithreadingDemo());
object.start();
}
}
}
A thread is a program in execution created to perform a specific task. Life cycle of a Java
thread starts with its birth and ends on its death.
The start() method of the Thread class is used to initiate the execution of a thread and it goes
into runnable state and the sleep() and wait() methods of the Thread class sends the thread
into non runnable state.
After non runnable state, thread again comes into runnable state and starts its execution. The
run() method of thread is very much important. After executing the run() method, the
lifecycle of thread is completed.
A thread is a path of execution in a program that goes through the following states of a
thread. The five states are as follows:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
When an instance of the Thread class is created a new thread is born and is known to be in
New-born state. That is, when a thread is born, it enters into new state but its execution phase
has not been started yet on the instance.
In simpler terms, Thread object is created but it cannot execute any program statement
because it is not in an execution state of the thread. Only start() method can be called on a
new thread; otherwise, an IllegalThreadStateException will be thrown.
Runnable State
The second phase of a new-born thread is the execution phase. When the start() method is
called on a the new instance of a thread, it enters into a runnable state.
In the runnable state, thread is ready for execution and is waiting for availability of the
processor (CPU time). There are many threads that are ready for execution, they all are
waiting in a queue (line).
If all threads have equal priority, a time slot is assigned for each thread execution on the basis
of first-come, first-serve manner by CPU. The process of allocating time to threads is known
as time slicing. A thread can come into runnable state from running, waiting, or new states.
Running State
Running means Processor (CPU) has allocated time slot to thread for its execution. When
thread scheduler selects a thread from the runnable state for execution, it goes into running
state. Look at the above figure.
In running state, processor gives its time to the thread for execution and executes its run
method. It is the state where thread performs its actual functions. A thread can come into
running state only from runnable state.
A running thread may give up its control in any one of the following situations and can enter
into the blocked state.
1. When sleep() method is invoked on a thread to sleep for specified time period, the
thread is out of queue during this time period. The thread again reenters into the
runnable state as soon as this time period is elapsed.
2. When a thread is suspended using suspend() method for some time in order to satisfy
some conditions. A suspended thread can be revived by using resume() method.
3. When wait() method is called on a thread to wait for some time. The thread in wait
state can be run again using notify() or notifyAll() method.
Blocked State
A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for
some time in order to satisfy some condition.
Dead State
A thread dies or moves into dead state automatically when its run() method completes the
execution of statements. That is, a thread is terminated or dead when a thread comes out of
run() method. A thread can also be dead when the stop() method is called.
During the life cycle of thread in Java, a thread moves from one state to another state in a
variety of ways. This is because in multithreading environment, when multiple threads are
executing, only one thread can use CPU at a time.
All other threads live in some other states, either waiting for their turn on CPU or waiting for
satisfying some conditions. Therefore, a thread is always in any of the five states.
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority
of the given thread.
FileName: ThreadPriorityExample.java
4. // Method 1
5. // Whenever the start() method is called by a thread
6. // the run() method is invoked
7. public void run()
8. {
9. // the print statement
10. System.out.println("Inside the run() method");
11. }
12.
13. // the main method
14. public static void main(String argvs[])
15. {
16. // Creating threads with the help of ThreadPriorityExample class
17. ThreadPriorityExample th1 = new ThreadPriorityExample();
18. ThreadPriorityExample th2 = new ThreadPriorityExample();
19. ThreadPriorityExample th3 = new ThreadPriorityExample();
20.
21. // We did not mention the priority of the thread.
22. // Therefore, the priorities of the thread is 5, the default value
23.
24. // 1st Thread
25. // Displaying the priority of the thread
26. // using the getPriority() method
27. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
28.
29. // 2nd Thread
30. // Display the priority of the thread
31. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
32.
33. // 3rd Thread
34. // // Display the priority of the thread
35. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
36.
37. // Setting priorities of above threads by
38. // passing integer arguments
39. th1.setPriority(6);
40. th2.setPriority(3);
41. th3.setPriority(9);
42.
43. // 6
44. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
45.
46. // 3
47. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
48.
49. // 9
50. System.out.println("Priority of the thread th3 is : " + th3.getPriority());
51.
52. // Main thread
53.
54. // Displaying name of the currently executing thread
55. System.out.println("Currently Executing The Thread : " + Thread.currentThread().get
Name());
56.
57. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());
58.
59. // Priority of the main thread is 10 now
60. Thread.currentThread().setPriority(10);
61.
62. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());
63. }
64. }
Deadlock in Java
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by another thread and second thread is waiting
for an object lock that is acquired by first thread. Since, both threads are waiting for each
other to release the lock, the condition is called deadlock.
TestDeadlockExample1.java
o wait()
o notify()
o notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.
Syntax:
3) notifyAll() method
Syntax:
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
Test.java
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Java Thread suspend() method
The suspend() method of thread class puts the thread from running to waiting state. This
method is used if you want to stop the thread execution and start it again when a certain event
occurs. This method allows a thread to temporarily cease execution. The suspended thread
can be resumed using the resume() method.
Syntax
1. public final void suspend()
Return
Exception
Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // suspend t2 thread
26. t2.suspend();
27. // call run() method
28. t3.start();
29. }
30. }
Java Thread resume() method
The resume() method of thread class is only used with suspend() method. This method is
used to resume a thread which was suspended using suspend() method. This method allows
the suspended thread to start again.
Syntax
1. public final void resume()
Return value
Exception
Example
1. public class JavaResumeExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaResumeExp t1=new JavaResumeExp ();
20. JavaResumeExp t2=new JavaResumeExp ();
21. JavaResumeExp t3=new JavaResumeExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. t2.suspend(); // suspend t2 thread
26. // call run() method
27. t3.start();
28. t2.resume(); // resume t2 thread
29. }
30. }
Java Thread stop() method
The stop() method of thread class terminates the thread execution. Once a thread is stopped,
it cannot be restarted by start() method.
Syntax
1. public final void stop()
2. public final void stop(Throwable obj)
Parameter
Return
Exception
SecurityException: This exception throws if the current thread cannot modify the thread.
Example
1. public class JavaStopExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaStopExp t1=new JavaStopExp ();
20. JavaStopExp t2=new JavaStopExp ();
21. JavaStopExp t3=new JavaStopExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // stop t3 thread
26. t3.stop();
27. System.out.println("Thread t3 is stopped");
28. }
29. }
Architecture of JDBC
Architecture of JDBC
Description:
1. Application: It is a java applet or a servlet that communicates with a data
source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important classes and interfaces
defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It uses
some database-specific drivers to effectively connect enterprise applications to
databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a
JDBC driver that intelligently communicates with the respective data source.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can
understand. JDBC drivers are the software components which implements interfaces in
JDBC APIs to enable java application to interact with the database. Now we will learn how
many JDBC driver types does Sun defines? There are four types of JDBC drivers defined
by Sun Microsystem that are mentioned below:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
1. JDBC-ODBC bridge driver – Type 1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. Type-1 driver is also called Universal driver because it can be used to connect to any
of the databases.
Advantages
This driver software is built-in with JDK so no need to install separately.
It is a database independent driver.
Disadvantages
As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
The ODBC bridge driver is needed to be installed in individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
2. Native-API driver – Type 2 driver ( Partially Java driver)
The Native API driver uses the client -side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver. This driver is not fully written in Java that is why it is also
called Partially Java driver.
Advantage
Native-API driver gives better performance than JDBC-ODBC bridge driver.
Disadvantages
Driver needs to be installed separately in individual client machines
The Vendor client library needs to be installed on client machine.
Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
It is a database dependent driver.
3. Network Protocol driver – Type 3 driver (fully Java driver)
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.
Advantages
Type-3 drivers are fully written in Java, hence they are portable drivers.
No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Switch facility to switch over from one database to another database.
Disadvantages
Network support is required on client machine.
Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4. Thin driver – Type 4 driver (fully Java driver)
Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known as
Thin Driver.
Advantages
Does not require any native library and Middleware server, so no client-side or server-
side installation.
It is fully written in Java language, hence they are portable drivers.
Disadvantage
If the database varies, then the driver will carry because it is database dependent.
The JDBC architecture consists of two-tier and three-tier processing models to access
a database. They are as described below:
2. Three-tier model: In this, the user’s queries are sent to middle-tier services,
from which the commands are again sent to the data source. The results are sent
back to the middle tier, and from there to the user.
This type of model is found very useful by management information system
directors.
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row
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:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}
packagecom.vinayak.jdbc;
importjava.sql.*;
publicclassJDBCDemo {
publicstaticvoidmain(String args[])
throwsSQLException, ClassNotFoundException
{
String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:XE";
String username = "scott";
String password = "tiger";
String query
= "insert into students values(109, 'bhatt')";
// Obtain a connection
Connection con = DriverManager.getConnection(
url, username, password);
// Obtain a statement
Statement st = con.createStatement();
The above example demonstrates the basic steps to access a database using JDBC. The
application uses the JDBC-ODBC bridge driver to connect to the database. You must
import java.sql package to provide basic SQL functionality and use the classes of the
package.
steps For Connectivity Between Java Program and Database
1. Import the Packages
2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections
Let us discuss these steps in brief before implementing by writing suitable code to illustrate
connectivity steps for JDBC/
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one
of two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new or
create objects. The following example uses Class.forName() to load the Oracle driver as
shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
user: Username from which your SQL command prompt can be accessed.
password: password from which the SQL command prompt can be accessed.
con: It is a reference to the Connection interface.
Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used, @localhost is the IP Address
where a 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 the programmer before
calling the function. Use of this can be referred to form the final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to
send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Note: Here, con is a reference to Connection interface used in previous step .
Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as follows:
The query for updating/inserting a table in a database.
The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet that can be
used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries
of updating/inserting.
Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is SQL query of the type String
Java
importjava.io.*;
importjava.sql.*;
classGFG {
publicstaticvoidmain(String[] args) throwsException
{
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSetrs
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db