Implementation (Working of JDBC)
- Suppose the database with which we want to deal is MySQL. So first we need to import the package, for SQL database it is namely ‘java.sql.*‘.
- Now as per IDE(we need to load its corresponding JAR file in our project in IDE where JAR is manually supposed to be inserted in the IDE, taking ‘eclipse IDE‘ for reference as an IDE in order to illustrate the same in the below example.
- By far we are done with importing the JAR to our project. Now in order to load the driver, we will be using forName() method by writing “com.mysql.driver_name” which belongs to class ‘class‘
Syntax:
class com.mysql.jdbc.Driver ;
- Now in order to establish the connection, we have to instantiate an interface named ‘Connection’
- Now statements are of three types:
- Normal statements:
- Prepared statements:
- Callable statements: Stored procedures
- Once the statement is created, now we will be executing the query in our database as per the perceived response from the database. Suppose if we want to fetch data from the database then the response is table structure here or if we are simply inserting the values then response if the number of rows effectively.
- Lastly, whatever we are getting either a table or simply rows, now we simply need to process the results.
- Also, it is recommended to good practice by closing the connections to release and free up memory resources by closing the object of interface and statement objects.
Illustration: Setting up JDBC
Java
// Java Program to Illustrate Setting Up of JDBC // Importing SQL database import java.sql.*; // Main class to illustrate demo of JDBC class GFG { // Main driver method public static void main(String[] args) throws Exception { // Loading and registering drivers // Optional from JDBC version 4.0 Class.forName( "oracle.jdbc.OracleDriver" ); // Step 2:Establishing a connection Connection con = DriverManager( "jdbc:oracle:thin:@localhost:1521:XE" , "username" , "password" ); // Step 3: Creating statement Statement st = con.createStatement(); // Step 4: Executing the query and storing the // result ResultSet rs = st.executeQuery( "select * from Students where Marks >= 70" ); // Step 5: Processing the results while (rs.next()) { System.out.println(rs.getString( "students" )); System.out.println(rs.getInt( "marks" )); } // Step 6: Closing the connections // using close() method to release memory resources con.close(); // Display message for successful execution of program System.out.println( "Steps in Setting Up of JDBC" ); } } |
Output
Steps in Setting Up of JDBC
Now let us move ahead and discuss its interaction with the real database after successfully setting up with the database how internally things are getting managed. Here we will be having to create two classes, one is our connection class and the other one where we will be implementing in application.java class using the connector object. We are done with the connection class in the above illustration, so let us now finally discuss the application class with help of an example. Considering the database ‘MySQL here to interpret and code out the same.
Implementation: Query in our MySQL database is as follows:
select * from Student;
insert into Students values(7, w3wiki);
select username from Student where userid = 7;
Example:
Java
// Java Program to Illustrate Working Of JDBC // with Above Query in Database // Importing required classes import java.io.*; import java.util.*; // Main class // JDBC demo class class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing arguments that // needed to be passed later in getConnection() String url = "jdbc:mysql://localhost/test" ; String uname = "root" ; String pass = "" ; // Query from the database taken // Custom query taken to illustrate String query = "select username from Student where id=7" ; // Loading and registering drivers Class.forName( "com.mysqljdbc.Driver" ); // Creating an connection object by // getConnection() method which is static method and // returns the instance of Connection class // This method takes 3 parameters as defined above Connection con = DriverManager.getConnection(url, uname, pass); Statement st = con.createStatement(); // It returns a tabular structure so we need // ResultSet as it stores chunk of data into // structures ResultSet rs = st.executeQuery(query); // Now we are having our data in object of ResultSet // which is no more tabular // Note: // Fetching the above data by storing it as a String // Here pointer is lagging with data for which we // use next() method to // take it to next record rs.next(); // Here we are fetching username column data String name = rs.getString( "username" ); // Lastly print the data System.out.println(name); // It is good practice to close the connection // using close() method // Closing the statement first st.close(); // Now close the connection also con.close(); } } |
Output
w3wiki
JDBC Tutorial
JDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes under java.sql package. In this Java JDBC tutorial, we will be learning about what is Java Database Connectivity with suitable example.
In the present world, where we mostly deal with websites and databases it is as if they matter the most but if we closely look over it is data that matters the most. If we look closer that all developers are revolving and working over the web and mobile technologies but what remains the same is the data.
Hence, there is an urgency to figure out how data is being handled for which this concept comes into play.
Let us do have an overview of why do we need this term which can be better interpreted with the image provided below.
Why do we need to learn advanced java?
As we are well versed with all the concepts of Core Java now comes the time to build projects that will results out in building an application as a final product. So if we do are only aware of core java we can only build applications that can be run on the machine where the components of it are stored(in simpler words one can say where all the codes are written). These types of applications are known as standalone applications.
Note: Standalone applications being one of two types of applications in the programming world only holds for 5% of the applications in the real world.
Hence, the scope is very constricted if we only do build standalone applications resulting out in the very little scope of development and scalability which gives birth to advance java which in turn gives birth to 3 components primarily namely JSP, Servlets, and JDBC in order to make the applications run on multiple machines. With the evolution of these 3 components, it removes the constraint of running only a single machine as it was impractical to users in the real-world application is made but forcing users to install then use them. Now, these types of applications are known as web applications that are the applications providing the services to the end-users without installing them. These applications are known as web applications which are not standalone applications.
Now you must be wondering what is JSP and Servlet and how JDBC is interrelated with them. For the time being, just focus only on JDBC in order to get started with what exactly it is and how to use it by referring to the image depicted below as follows:
Note: Conclusion drawn from Image is as follows:
- JSP stands for Java Server Pages where these pages are considered as View Components as Presentation logic.
- Servlet is meant for internal processing going on such as reading, fetching values from the database, comparison, etc in the backend as Processing Logic in our process servlet. Servlets do also contain java classes for this background processing for processing logic.
- JDBC is meant for Connectivity of Java Application in servlets as discussed to our Database.