0% found this document useful (0 votes)
13 views23 pages

What Is JDBC

Uploaded by

Abinet Bizuayehu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views23 pages

What Is JDBC

Uploaded by

Abinet Bizuayehu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

What is JDBC?

• JDBC stands for Java Database Connectivity, which is a


standard Java API for database-independent connectivity
between the Java programming language and a wide range of
databases.
• JDBC is an interface which allows Java code to execute SQL
statements inside relational databases.
• The JDBC library includes APIs for each of the tasks commonly
associated with database usage:
– Making a connection to a database
– Creating SQL or MySQL statements
– Executing that SQL or MySQL queries in the database
– Viewing & Modifying the resulting records
Continued…
• All JDBC programs do the following:
• Step 1) import and load the JDBC driver
• Step 2) Specify the name and location of the
database being used
• Step 3) Connect to the database with a Connection
object
• Step 4) Execute a SQL query using a Statement
object
• Step 5) Get the results in a ResultSet object
• Step 6) Finish by closing the ResultSet, Statement
and Connection objects
Creating JDBC Application

• There are six steps involved in building a JDBC


application.
• Import the packages:
• This requires that you include the packages
containing the JDBC classes needed for database
programming.
• Most often, using import java.sql.* will suffice as
follows:
• //STEP 1. Import required packages
• import java.sql.*;
Register the JDBC driver
• This requires that you initialize a driver so you
can open a communications channel with the
database. Following is the code snippet to
achieve this:
• //STEP 2: Register JDBC driver
• Class.forName("com.mysql.jdbc.Driver");
Open a connection:

• This requires using the


DriverManager.getConnection() method to
create a Connection object, which represents
a physical connection with the database as
follows:
Continued…
• //STEP 3: Open a connection
• // Database credentials
• static final String USER = "username";
• static final String PASS = "password";
• System.out.println("Connecting to database...");
• conn =
DriverManager.getConnection(DB_URL,USER,PASS);
Execute a query
• This requires using an object of type
Statement or PreparedStatement for building
and submitting an SQL statement to the
database as follows:
• //STEP 4: Execute a query
• System.out.println("Creating statement...");
• stmt = conn.createStatement();
• String sql;
Continued…
• sql = "SELECT id, first, last, age FROM Employees";
• ResultSet rs = stmt.executeQuery(sql);
• If there is an SQL UPDATE,INSERT or DELETE
statement required, then following code snippet
would be required:
• //STEP 4: Execute a query
• System.out.println("Creating statement...");
• stmt = conn.createStatement();
• String sql;
• sql = "DELETE FROM Employees";
• ResultSet rs = stmt.executeUpdate(sql);
Extract data from result set
• This step is required in case you are fetching data from
the database.
• You can use the appropriate ResultSet.getXXX() method
to retrieve the data from the result set as follows:
• //STEP 5: Extract data from result set
• while(rs.next()){
• //Retrieve by column name
• int id = rs.getInt("id");
• int age = rs.getInt("age");
• String first = rs.getString("first");
• String last = rs.getString("last");
Continued…
• //Display values
• System.out.print("ID: " + id);
• System.out.print(", Age: " + age);
• System.out.print(", First: " + first);
• System.out.println(", Last: " + last);
• }
Clean up the environment
• You should explicitly close all database
resources versus relying on the JVM's garbage
collection as follows: //STEP 6: Clean-up
environment
• rs.close();
• stmt.close();
• conn.close();
Sample JDBC Program
• Based on the above steps, we can have
following consolidated sample code which we
can use as a template while writing our JDBC
code:
• This sample code has been written based on
the environment and database setup done in
Environment chapter.
Continued…
• //STEP 1. Import required packages
• import java.sql.*;
• public class FirstExample {
• // JDBC driver name and database URL
• static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
• static final String DB_URL = "jdbc:mysql://localhost:3306/user";
• // Database credentials
• static final String USER = "username";
• static final String PASS = "password";
• public static void main(String[] args) {
• Connection conn = null;
• Statement stmt = null;
Continued…
• try{
• //STEP 2: Register JDBC driver
• Class.forName("com.mysql.jdbc.Driver");
• //STEP 3: Open a connection
• System.out.println("Connecting to database...");
• conn = DriverManager.getConnection(DB_URL,USER,PASS);
• //STEP 4: Execute a query
• System.out.println("Creating statement...");
• stmt = conn.createStatement();
• String sql;
• sql = "SELECT sid, sname, smarks FROM student";
• ResultSet rs = stmt.executeQuery(sql);
Continued…
• //STEP 5: Extract data from result set
• while(rs.next()){
• //Retrieve by column name
• int id = rs.getInt("sid");
• String name= rs.getString("sname");
• int mark = rs.getInt("smarks");
• //Display values
• System.out.println(" ID: " + id);
• System.out.println(“ Name: " + name);
• System.out.println(“ Mark: " + mark);
• System.out.println();

• }
Continued…
• //STEP 6: Clean-up environment
• rs.close();
• stmt.close();
• conn.close();
• }catch(SQLException se){
• //Handle errors for JDBC
• se.printStackTrace();
• }catch(Exception e){
• //Handle errors for Class.forName
• e.printStackTrace();
• }finally{
• //finally block used to close resources
Continued…
• try{
• if(stmt!=null)
• stmt.close();
• }catch(SQLException se2){
• }// nothing we can do
• try{
• if(conn!=null)
• conn.close();
• }catch(SQLException se){
• se.printStackTrace();
• }//end finally try
• }//end try
Continued…
• System.out.println("Goodbye!");
• }//end main
• }//end FirstExample
• Now let us compile above example as follows:
• C:\>javac FirstExample.java
• C:\>
Continued…
• When you run FirstExample, it produces following result:
• C:\>java FirstExample
• Connecting to database...
• Creating statement...
• ID: 1
• Name: Abebe
• Mark:80

• ID: 2
• Name: kebede
• Mark: 90
• C:\>
Example2
• import java.sql.*;
• public class SqlTest
• {
• public static void main(String[] args)
• {
• try
• {
• // Step 1: Make a connection
• // Load the driver
• Class.forName("com.mysql.jdbc.Driver");
• // Get a connection using this driver
• String url = "jdbc:mysql://localhost/user";
• String dbUser = "root";
• String dbPassword = "9818";
Continued..
• Connection con = DriverManager.getConnection(url, dbUser, dbPassword);
• Statement stmt = con.createStatement();
• String sql= "SELECT * FROM student";
• ResultSet rs = stmt.executeQuery(sql);
• int id;
• String name;
• int marks;
• while (rs.next())
• {
• id = rs.getInt("sid");
• name = rs.getString("sname");
• marks = rs.getInt("smarks");
Continued…
• System.out.println("Id= "+id+"name = " + name + " marks = " + marks);
• }
• stmt.close();
• con.close();
• }
• catch(ClassNotFoundException ex1)
• {
• System.out.println(ex1);
• }
• catch(SQLException ex2)
• {
• System.out.println(ex2);
• }
• }
• }
Continued…
• Now let us compile above example as follows:
• C:\>javac SqlTest.java
• C:\>java SqlTest
• ID = 1 name =Abebe marks= 80
• ID = 2 name = Kebede marks=90
• C:\>

You might also like