SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Tutorials Point, Simply Easy Learning

                                     JDBC Tutorial

                                 Tutorialspoint.com
The JDBC API is a Java API that can access any kind of tabular data, especially data
stored in a Relational Database. JDBC stands for Java Database Connectivity.

JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX. This tutorial gives an initial push to start you with log4J. For
more detail kindly check tutorialspoint.com/jdbc


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.

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


Pre-Requisite:
You need to have good understanding on the following two subjects to learn JDBC:

    1.   Core JAVA Programming
    2.   SQL or MySQL Database


JDBC - Environment Setup:
Make sure you have done following setup:

    1.   Core JAVA Installation
    2.   SQL or MySQL Database Installation

Apart from the above you need to setup a database which you would use for your project.
Assuming this is EMP and you have created on table Employees within the same database.


Creating JDBC Application:
There are six steps involved in building a JDBC application which I'm going to brief in this
tutorial:


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.*;


1|Page
Tutorials Point, Simply Easy Learning

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:


//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;
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");



2|Page
Tutorials Point, Simply Easy Learning

     //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();


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.


//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/EMP";

    // Database credentials
    static final String USER = "username";
    static final String PASS = "password";

    public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    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 id, first, last, age FROM Employees";
       ResultSet rs = stmt.executeQuery(sql);

       //STEP 5: Extract data from result set
       while(rs.next()){
          //Retrieve by column name


3|Page
Tutorials Point, Simply Easy Learning

           int id = rs.getInt("id");
           int age = rs.getInt("age");
           String first = rs.getString("first");
           String last = rs.getString("last");

           //Display values
           System.out.print("ID: " + id);
           System.out.print(", Age: " + age);
           System.out.print(", First: " + first);
           System.out.println(", Last: " + last);
      }
      //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
      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
   System.out.println("Goodbye!");
}//end main
}//end FirstExample


Now let us compile above example as follows:


C:>javac FirstExample.java
C:>


When you run FirstExample, it produces following result:


C:>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:>


SQLException Methods:


4|Page
Tutorials Point, Simply Easy Learning
A SQLException can occur both in the driver and the database. When such an exception occurs,
an object of type SQLException will be passed to the catch clause.

The passed SQLException object has the following methods available for retrieving additional
information about the exception:


                  Method                                       Description


getErrorCode( )                          Gets the error number associated with the exception.


getMessage( )                            Gets the JDBC driver's error message for an error
                                         handled by the driver or gets the Oracle error number
                                         and message for a database error.


getSQLState( )                           Gets the XOPEN SQLstate string. For a JDBC driver
                                         error, no useful information is returned from this
                                         method. For a database error, the five-digit XOPEN
                                         SQLstate code is returned. This method can return
                                         null.


getNextException( )                      Gets the next Exception object in the exception chain.


printStackTrace( )                       Prints the current exception, or throwable, and its
                                         backtrace to a standard error stream.


printStackTrace(PrintStream s)           Prints this throwable and its backtrace to the print
                                         stream you specify.


printStackTrace(PrintWriter w)           Prints this throwable and its backtrace to the print
                                         writer you specify.



By utilizing the information available from the Exception object, you can catch an exception and
continue your program appropriately. Here is the general form of a try block:


try {
   // Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
   // Your exception handling code goes between these
   // curly braces, similar to the exception clause
   // in a PL/SQL block.
}
finally {
   // Your must-always-be-executed code goes between these
   // curly braces. Like closing database connection.
}


JDBC - Data Types:



5|Page
Tutorials Point, Simply Easy Learning
The following table summarizes the default JDBC data type that the Java data type is converted
to when you call the setXXX() method of the PreparedStatement or CallableStatement object or
the ResultSet.updateXXX() method.


          SQL                  JDBC/Java                 setXXX             updateXXX


VARCHAR                java.lang.String        setString               updateString


CHAR                   java.lang.String        setString               updateString


LONGVARCHAR            java.lang.String        setString               updateString


BIT                    boolean                 setBoolean              updateBoolean


NUMERIC                java.math.BigDecimal    setBigDecimal           updateBigDecimal


TINYINT                byte                    setByte                 updateByte


SMALLINT               short                   setShort                updateShort


INTEGER                int                     setInt                  updateInt


BIGINT                 long                    setLong                 updateLong


REAL                   float                   setFloat                updateFloat


FLOAT                  float                   setFloat                updateFloat


DOUBLE                 double                  setDouble               updateDouble


VARBINARY              byte[ ]                 setBytes                updateBytes


BINARY                 byte[ ]                 setBytes                updateBytes


DATE                   java.sql.Date           setDate                 updateDate


TIME                   java.sql.Time           setTime                 updateTime


TIMESTAMP              java.sql.Timestamp      setTimestamp            updateTimestamp


CLOB                   java.sql.Clob           setClob                 updateClob


BLOB                   java.sql.Blob           setBlob                 updateBlob




6|Page
Tutorials Point, Simply Easy Learning

ARRAY                  java.sql.Array          setARRAY                updateARRAY


REF                    java.sql.Ref            SetRef                  updateRef


STRUCT                 java.sql.Struct         SetStruct               updateStruct



JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet
object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that
enable you to directly manipulate the respective data on the server.

The setXXX() and updateXXX() methods enable you to convert specific Java types to specific
JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any
Java type to a JDBC data type.

ResultSet object provides corresponding getXXX() method for each data type to retrieve column
value. Each method can be used with column name or by its ordinal position.


          SQL                  JDBC/Java                setXXX                  getXXX


VARCHAR                java.lang.String        setString               getString


CHAR                   java.lang.String        setString               getString


LONGVARCHAR            java.lang.String        setString               getString


BIT                    boolean                 setBoolean              getBoolean


NUMERIC                java.math.BigDecimal    setBigDecimal           getBigDecimal


TINYINT                byte                    setByte                 getByte


SMALLINT               short                   setShort                getShort


INTEGER                int                     setInt                  getInt


BIGINT                 long                    setLong                 getLong


REAL                   float                   setFloat                getFloat


FLOAT                  float                   setFloat                getFloat


DOUBLE                 double                  setDouble               getDouble


VARBINARY              byte[ ]                 setBytes                getBytes




7|Page
Tutorials Point, Simply Easy Learning

BINARY                    byte[ ]                  setBytes                getBytes


DATE                      java.sql.Date            setDate                 getDate


TIME                      java.sql.Time            setTime                 getTime


TIMESTAMP                 java.sql.Timestamp       setTimestamp            getTimestamp


CLOB                      java.sql.Clob            setClob                 getClob


BLOB                      java.sql.Blob            setBlob                 getBlob


ARRAY                     java.sql.Array           setARRAY                getARRAY


REF                       java.sql.Ref             SetRef                  getRef


STRUCT                    java.sql.Struct          SetStruct               getStruct




JDBC - Create Database Example
This tutorial provides an example on how to create a Database using JDBC application. Before
executing following example, make sure you have the following in place:


          You should have admin privilege to create a database in the given schema. To execute
           the following example you need to replace username and password with your actual
           user name and password.
          Your MySQL or whatever database you are using is up and running.


Required Steps:
There are following steps required to create a new Database using JDBC application:

      1.   Import the packages . Requires that you include the packages containing the JDBC
           classes needed for database programming. Most often, using import java.sql.* will
           suffice.
      2.   Register the JDBC driver . Requires that you initialize a driver so you can open a
           communications channel with the database.
      3.   Open a connection . Requires using the DriverManager.getConnection() method to
           create a Connection object, which represents a physical connection with datbase server.

           To create a new database, you need not to give any database name while preparing
           database URL as mentioned in the below example.

      4.   Execute a query . Requires using an object of type Statement for building and
           submitting an SQL statement to the database.
      5.   Clean up the environment . Requires explicitly closing all database resources versus
           relying on the JVM's garbage collection.


Sample Code:


8|Page
Tutorials Point, Simply Easy Learning
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   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 database...");
       stmt = conn.createStatement();

      String sql = "CREATE DATABASE STUDENTS";
      stmt.executeUpdate(sql);
      System.out.println("Database created successfully...");
   }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
      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
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>


9|Page
Tutorials Point, Simply Easy Learning
When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to database...
Creating database...
Database created successfully...
Goodbye!
C:>


JDBC - Select Database Example
This tutorial provides an example on how to select a Database using JDBC application. Before
executing following example, make sure you have the following in place:


        To execute the following example you need to replace username and password with
         your actual user name and password.
        Your MySQL or whatever database you are using is up and running.


Required Steps:
There are following steps required to create a new Database using JDBC application:

    1.   Import the packages . Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver . Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection . Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a selected
         database.

         Selection of database is made while you prepare database URL. Following example
         would make connection with STUDENTS database.

    4.   Clean up the environment . Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   try{


10 | P a g e
Tutorials Point, Simply Easy Learning

        //STEP 2: Register JDBC driver
        Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");
   }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
      try{
         if(conn!=null)
             conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>


When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Goodbye!
C:>


JDBC - Drop Database Example
This tutorial provides an example on how to drop an existing Database using JDBC application.
Before executing following example, make sure you have the following in place:


       To execute the following example you need to replace username and password with
        your actual user name and password.
       Your MySQL or whatever database you are using is up and running.

NOTE: This is a serious operation and you have to make a firm decision before proceeding to
delete a database because everything you have in your database would be lost.


Required Steps:
There are following steps required to create a new Database using JDBC application:




11 | P a g e
Tutorials Point, Simply Easy Learning
    1.   Import the packages: Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver: Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection: Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a database
         server.

         Deleting a database does not require database name to be in your database URL.
         Following example would delete STUDENTS database.

    4.   Execute a query: Requires using an object of type Statement for building and
         submitting an SQL statement to delete the database.
    5.   Clean up the environment . Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

         //STEP 3: Open a connection
         System.out.println("Connecting to a selected database...");
         conn = DriverManager.getConnection(DB_URL, USER, PASS);
         System.out.println("Connected database successfully...");

         //STEP 4: Execute a query
         System.out.println("Deleting database...");
         stmt = conn.createStatement();

      String sql = "DROP DATABASE STUDENTS";
      stmt.executeUpdate(sql);
      System.out.println("Database deleted successfully...");
   }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


12 | P a g e
Tutorials Point, Simply Easy Learning

      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>


When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Deleting database...
Database deleted successfully...
Goodbye!
C:>


JDBC - Create Tables Example
This tutorial provides an example on how to create a table using JDBC application. Before
executing following example, make sure you have the following in place:


        To execute the following example you can replace username and password with your
         actual user name and password.
        Your MySQL or whatever database you are using is up and running.


Required Steps:
There are following steps required to create a new Database using JDBC application:

    1.   Import the packages: Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver: Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection: Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a database
         server.
    4.   Execute a query: Requires using an object of type Statement for building and
         submitting an SQL statement to create a table in a seleted database.
    5.   Clean up the environment . Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


13 | P a g e
Tutorials Point, Simply Easy Learning

Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

       //STEP 3: Open a connection
       System.out.println("Connecting to a selected database...");
       conn = DriverManager.getConnection(DB_URL, USER, PASS);
       System.out.println("Connected database successfully...");

       //STEP 4: Execute a query
       System.out.println("Creating table in given database...");
       stmt = conn.createStatement();

       String sql = "CREATE TABLE REGISTRATION " +
                    "(id INTEGER not NULL, " +
                    " first VARCHAR(255), " +
                    " last VARCHAR(255), " +
                    " age INTEGER, " +
                    " PRIMARY KEY ( id ))";

      stmt.executeUpdate(sql);
      System.out.println("Created table in given database...");
   }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
      try{
         if(stmt!=null)
             conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
             conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try


14 | P a g e
Tutorials Point, Simply Easy Learning

   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>


When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating table in given database...
Created table in given database...
Goodbye!
C:>


JDBC - Drop Tables Example
This tutorial provides an example on how to delete a table using JDBC application. Before
executing following example, make sure you have the following in place:


        To execute the following example you can replace username and password with your
         actual user name and password.
        Your MySQL or whatever database you are using is up and running.

NOTE: This is a serious operation and you have to make a firm decision before proceeding to
delete a table because everything you have in your table would be lost.


Required Steps:
There are following steps required to create a new Database using JDBC application:

    1.   Import the packages: Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver: Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection: Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a database
         server.
    4.   Execute a query: Requires using an object of type Statement for building and
         submitting an SQL statement to drop a table in a seleted database.
    5.   Clean up the environment . Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages


15 | P a g e
Tutorials Point, Simply Easy Learning

import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

       //STEP 3: Open a connection
       System.out.println("Connecting to a selected database...");
       conn = DriverManager.getConnection(DB_URL, USER, PASS);
       System.out.println("Connected database successfully...");

       //STEP 4: Execute a query
       System.out.println("Deleting table in given database...");
       stmt = conn.createStatement();

       String sql = "DROP TABLE REGISTRATION ";

      stmt.executeUpdate(sql);
      System.out.println("Table deleted in given database...");
   }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
      try{
         if(stmt!=null)
             conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
             conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>



16 | P a g e
Tutorials Point, Simply Easy Learning
When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Deleting table in given database...
Table deleted in given database...
Goodbye!
C:>


JDBC - Insert Records Example
This tutorial provides an example on how to insert records in a table using JDBC application.
Before executing following example, make sure you have the following in place:


        To execute the following example you can replace username and password with your
         actual user name and password.
        Your MySQL or whatever database you are using is up and running.


Required Steps:
There are following steps required to create a new Database using JDBC application:

    1.   Import the packages: Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver: Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection: Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a database
         server.
    4.   Execute a query: Requires using an object of type Statement for building and
         submitting an SQL statement to insert records into a table.
    5.   Clean up the environment: Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver


17 | P a g e
Tutorials Point, Simply Easy Learning

       Class.forName("com.mysql.jdbc.Driver");

       //STEP 3: Open a connection
       System.out.println("Connecting to a selected database...");
       conn = DriverManager.getConnection(DB_URL, USER, PASS);
       System.out.println("Connected database successfully...");

       //STEP 4: Execute a query
       System.out.println("Inserting records into the table...");
       stmt = conn.createStatement();

       String sql = "INSERT INTO Registration " +
                    "VALUES (100, 'Zara', 'Ali', 18)";
       stmt.executeUpdate(sql);
       sql = "INSERT INTO Registration " +
                    "VALUES (101, 'Mahnaz', 'Fatma', 25)";
       stmt.executeUpdate(sql);
       sql = "INSERT INTO Registration " +
                    "VALUES (102, 'Zaid', 'Khan', 30)";
       stmt.executeUpdate(sql);
       sql = "INSERT INTO Registration " +
                    "VALUES(103, 'Sumit', 'Mittal', 28)";
       stmt.executeUpdate(sql);
       System.out.println("Inserted records into the table...");

   }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
      try{
         if(stmt!=null)
             conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
             conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>


When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...

18 | P a g e
Tutorials Point, Simply Easy Learning

Inserting records into the table...
Inserted records into the table...
Goodbye!
C:>


JDBC - Select Records Example
This tutorial provides an example on how to select/ fetch records from a table using JDBC
application. Before executing following example, make sure you have the following in place:


        To execute the following example you can replace username and password with your
         actual user name and password.
        Your MySQL or whatever database you are using is up and running.


Required Steps:
There are following steps required to create a new Database using JDBC application:

    1.   Import the packages: Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver: Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection: Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a database
         server.
    4.   Execute a query: Requires using an object of type Statement for building and
         submitting an SQL statement to select (i.e. fetch ) records from a table.
    5.   Extract Data: Once SQL query is executed, you can fetch records from the table.
    6.   Clean up the environment: Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

         //STEP 3: Open a connection
         System.out.println("Connecting to a selected database...");


19 | P a g e
Tutorials Point, Simply Easy Learning

       conn = DriverManager.getConnection(DB_URL, USER, PASS);
       System.out.println("Connected database successfully...");

       //STEP 4: Execute a query
       System.out.println("Creating statement...");
       stmt = conn.createStatement();

       String sql = "SELECT id, first, last, age FROM Registration";
       ResultSet rs = stmt.executeQuery(sql);
       //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");

           //Display values
           System.out.print("ID: " + id);
           System.out.print(", Age: " + age);
           System.out.print(", First: " + first);
           System.out.println(", Last: " + last);
      }
      rs.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
      try{
         if(stmt!=null)
             conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
             conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>


When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating statement...

20 | P a g e
Tutorials Point, Simply Easy Learning

ID: 100,    Age:   18,   First:   Zara, Last: Ali
ID: 101,    Age:   25,   First:   Mahnaz, Last: Fatma
ID: 102,    Age:   30,   First:   Zaid, Last: Khan
ID: 103,    Age:   28,   First:   Sumit, Last: Mittal
Goodbye!
C:>


JDBC - Update Records Example
This tutorial provides an example on how to update records in a table using JDBC application.
Before executing following example, make sure you have the following in place:


        To execute the following example you can replace username and password with your
         actual user name and password.
        Your MySQL or whatever database you are using is up and running.


Required Steps:
There are following steps required to create a new Database using JDBC application:

    1.   Import the packages: Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver: Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection: Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a database
         server.
    4.   Execute a query: Requires using an object of type Statement for building and
         submitting an SQL statement to update records in a table. This Query makes use of IN
         and WHERE clause to update conditional records.
    5.   Clean up the environment: Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");



21 | P a g e
Tutorials Point, Simply Easy Learning

       //STEP 3: Open a connection
       System.out.println("Connecting to a selected database...");
       conn = DriverManager.getConnection(DB_URL, USER, PASS);
       System.out.println("Connected database successfully...");

       //STEP 4: Execute a query
       System.out.println("Creating statement...");
       stmt = conn.createStatement();
       String sql = "UPDATE Registration " +
                    "SET age = 30 WHERE id in (100, 101)";
       stmt.executeUpdate(sql);

       // Now you can extract all the records
       // to see the updated records
       sql = "SELECT id, first, last, age FROM Registration";
       ResultSet rs = stmt.executeQuery(sql);

       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");

           //Display values
           System.out.print("ID: " + id);
           System.out.print(", Age: " + age);
           System.out.print(", First: " + first);
           System.out.println(", Last: " + last);
      }
      rs.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
      try{
         if(stmt!=null)
             conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
             conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>



22 | P a g e
Tutorials Point, Simply Easy Learning
When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating statement...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!
C:>


JDBC - Delete Records Example
This tutorial provides an example on how to delete records from a table using JDBC application.
Before executing following example, make sure you have the following in place:


        To execute the following example you can replace username and password with your
         actual user name and password.
        Your MySQL or whatever database you are using is up and running.


Required Steps:
There are following steps required to create a new Database using JDBC application:

    1.   Import the packages: Requires that you include the packages containing the JDBC
         classes needed for database programming. Most often, using import java.sql.* will
         suffice.
    2.   Register the JDBC driver: Requires that you initialize a driver so you can open a
         communications channel with the database.
    3.   Open a connection: Requires using the DriverManager.getConnection() method to
         create a Connection object, which represents a physical connection with a database
         server.
    4.   Execute a query: Requires using an object of type Statement for building and
         submitting an SQL statement to delete records from a table. This Query makes use of
         WHERE clause to delete conditional records.
    5.   Clean up the environment: Requires explicitly closing all database resources versus
         relying on the JVM's garbage collection.


Sample Code:
Copy and past following example in JDBCExample.java, compile and run as follows:


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {


23 | P a g e
Tutorials Point, Simply Easy Learning

   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

       //STEP 3: Open a connection
       System.out.println("Connecting to a selected database...");
       conn = DriverManager.getConnection(DB_URL, USER, PASS);
       System.out.println("Connected database successfully...");

       //STEP 4: Execute a query
       System.out.println("Creating statement...");
       stmt = conn.createStatement();
       String sql = "DELETE FROM Registration " +
                    "WHERE id = 101";
       stmt.executeUpdate(sql);

       // Now you can extract all the records
       // to see the remaining records
       sql = "SELECT id, first, last, age FROM Registration";
       ResultSet rs = stmt.executeQuery(sql);

       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");

           //Display values
           System.out.print("ID: " + id);
           System.out.print(", Age: " + age);
           System.out.print(", First: " + first);
           System.out.println(", Last: " + last);
      }
      rs.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
      try{
         if(stmt!=null)
             conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
             conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample



24 | P a g e
Tutorials Point, Simply Easy Learning
Now let us compile above example as follows:


C:>javac JDBCExample.java
C:>


When you run JDBCExample, it produces following result:


C:>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating statement...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!
C:>


JDBC - Batch Processing:
Batch Processing allows you to group related SQL statements into a batch and submit them with
one call to the database.

When you send several SQL statements to the database at once, you reduce the amount of
communication overhead, thereby improving performance.


        JDBC drivers are not required to support this feature. You should use the
         DatabaseMetaData.supportsBatchUpdates() method to determine if the target database
         supports batch update processing. The method returns true if your JDBC driver
         supports this feature.
        The addBatch() method of Statement, PreparedStatement, and CallableStatement is
         used to add individual statements to the batch. The executeBatch() is used to start
         the execution of all the statements grouped together.
        The executeBatch() returns an array of integers, and each element of the array
         represents the update count for the respective update statement.
        Just as you can add statements to a batch for processing, you can remove them with
         the clearBatch() method. This method removes all the statements you added with the
         addBatch() method. However, you cannot selectively choose which statement to
         remove.


JDBC - Streaming Data:
A PreparedStatement object has the ability to use input and output streams to supply parameter
data. This enables you to place entire files into database columns that can hold large values,
such as CLOB and BLOB data types.

There are following methods which can be used to stream data:

    1.   setAsciiStream(): This method is used to supply large ASCII values.
    2.   setCharacterStream(): This method is used to supply large UNICODE values.
    3.   setBinaryStream(): This method is used to supply large binary values.

The setXXXStream() method requires an extra parameter, the file size, besides the parameter
placeholder. This parameter informs the driver how much data should be sent to the database
using the stream.


Further Detail:

25 | P a g e
Tutorials Point, Simply Easy Learning

Refer to the link http://www.tutorialspoint.com/jdbc


                List of Tutorials from TutorialsPoint.com
       Learn JSP                          Learn ASP.Net
       Learn Servlets                     Learn HTML
       Learn log4j                        Learn HTML5
       Learn iBATIS                       Learn XHTML
       Learn Java                         Learn CSS
       Learn JDBC                         Learn HTTP
       Java Examples                      Learn JavaScript
       Learn Best Practices               Learn jQuery
       Learn Python                       Learn Prototype
       Learn Ruby                         Learn script.aculo.us
       Learn Ruby on Rails                Web Developer's Guide
       Learn SQL                          Learn RADIUS
       Learn MySQL                        Learn RSS
       Learn AJAX                         Learn SEO Techniques
       Learn C Programming                Learn SOAP
       Learn C++ Programming              Learn UDDI
       Learn CGI with PERL                Learn Unix Sockets
       Learn DLL                          Learn Web Services
       Learn ebXML                        Learn XML-RPC
       Learn Euphoria                     Learn UML
       Learn GDB Debugger                 Learn UNIX
       Learn Makefile                     Learn WSDL
       Learn Parrot                       Learn i-Mode
       Learn Perl Script                  Learn GPRS
       Learn PHP Script                   Learn GSM
       Learn Six Sigma                    Learn WAP
       Learn SEI CMMI                     Learn WML
       Learn WiMAX                        Learn Wi-Fi
       Learn Telecom Billing
                     webmaster@TutorialsPoint.com




26 | P a g e
Tutorials Point, Simply Easy Learning




27 | P a g e

Weitere ähnliche Inhalte

Was ist angesagt?

Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENG
Dmitry Evteev
 
Session 6 Tp6
Session 6 Tp6Session 6 Tp6
Session 6 Tp6
phanleson
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
Ashwin Kumar
 

Was ist angesagt? (20)

Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
Lecture17
Lecture17Lecture17
Lecture17
 
Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks
 
Advanced Sql Injection ENG
Advanced Sql Injection ENGAdvanced Sql Injection ENG
Advanced Sql Injection ENG
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
 
Database security
Database securityDatabase security
Database security
 
Sql interview questions
Sql interview questionsSql interview questions
Sql interview questions
 
SQL2SPARQL
SQL2SPARQLSQL2SPARQL
SQL2SPARQL
 
lab56_db
lab56_dblab56_db
lab56_db
 
[Blackhat2015] FileCry attack against Java
[Blackhat2015] FileCry attack against Java[Blackhat2015] FileCry attack against Java
[Blackhat2015] FileCry attack against Java
 
treeview
treeviewtreeview
treeview
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Session 6 Tp6
Session 6 Tp6Session 6 Tp6
Session 6 Tp6
 
Ebook8
Ebook8Ebook8
Ebook8
 
A Brief Introduction About Sql Injection in PHP and MYSQL
A Brief Introduction About Sql Injection in PHP and MYSQLA Brief Introduction About Sql Injection in PHP and MYSQL
A Brief Introduction About Sql Injection in PHP and MYSQL
 
Blocks In Drupal
Blocks In DrupalBlocks In Drupal
Blocks In Drupal
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 

Andere mochten auch

Andere mochten auch (14)

Java server pages
Java server pagesJava server pages
Java server pages
 
Simple tutorial for using jdbc
Simple tutorial for using jdbcSimple tutorial for using jdbc
Simple tutorial for using jdbc
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)
 
Servlet and jsp development with eclipse wtp
Servlet and jsp development with eclipse wtpServlet and jsp development with eclipse wtp
Servlet and jsp development with eclipse wtp
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Angular js 1.3 basic tutorial
Angular js 1.3 basic tutorialAngular js 1.3 basic tutorial
Angular js 1.3 basic tutorial
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
 
java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 

Ähnlich wie Jdbc tutorial

30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
phanleson
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 

Ähnlich wie Jdbc tutorial (20)

Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Database connect
Database connectDatabase connect
Database connect
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
22jdbc
22jdbc22jdbc
22jdbc
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Sql exception and class notfoundexception
Sql exception and class notfoundexceptionSql exception and class notfoundexception
Sql exception and class notfoundexception
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Jdbc tutorial

  • 1. Tutorials Point, Simply Easy Learning JDBC Tutorial Tutorialspoint.com The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC stands for Java Database Connectivity. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives an initial push to start you with log4J. For more detail kindly check tutorialspoint.com/jdbc 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. 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 Pre-Requisite: You need to have good understanding on the following two subjects to learn JDBC: 1. Core JAVA Programming 2. SQL or MySQL Database JDBC - Environment Setup: Make sure you have done following setup: 1. Core JAVA Installation 2. SQL or MySQL Database Installation Apart from the above you need to setup a database which you would use for your project. Assuming this is EMP and you have created on table Employees within the same database. Creating JDBC Application: There are six steps involved in building a JDBC application which I'm going to brief in this tutorial: 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.*; 1|Page
  • 2. Tutorials Point, Simply Easy Learning 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: //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; 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"); 2|Page
  • 3. Tutorials Point, Simply Easy Learning //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(); 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. //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/EMP"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; 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 id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name 3|Page
  • 4. Tutorials Point, Simply Easy Learning int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } //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 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 System.out.println("Goodbye!"); }//end main }//end FirstExample Now let us compile above example as follows: C:>javac FirstExample.java C:> When you run FirstExample, it produces following result: C:>java FirstExample Connecting to database... Creating statement... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:> SQLException Methods: 4|Page
  • 5. Tutorials Point, Simply Easy Learning A SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause. The passed SQLException object has the following methods available for retrieving additional information about the exception: Method Description getErrorCode( ) Gets the error number associated with the exception. getMessage( ) Gets the JDBC driver's error message for an error handled by the driver or gets the Oracle error number and message for a database error. getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null. getNextException( ) Gets the next Exception object in the exception chain. printStackTrace( ) Prints the current exception, or throwable, and its backtrace to a standard error stream. printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you specify. printStackTrace(PrintWriter w) Prints this throwable and its backtrace to the print writer you specify. By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block: try { // Your risky code goes between these curly braces!!! } catch(Exception ex) { // Your exception handling code goes between these // curly braces, similar to the exception clause // in a PL/SQL block. } finally { // Your must-always-be-executed code goes between these // curly braces. Like closing database connection. } JDBC - Data Types: 5|Page
  • 6. Tutorials Point, Simply Easy Learning The following table summarizes the default JDBC data type that the Java data type is converted to when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method. SQL JDBC/Java setXXX updateXXX VARCHAR java.lang.String setString updateString CHAR java.lang.String setString updateString LONGVARCHAR java.lang.String setString updateString BIT boolean setBoolean updateBoolean NUMERIC java.math.BigDecimal setBigDecimal updateBigDecimal TINYINT byte setByte updateByte SMALLINT short setShort updateShort INTEGER int setInt updateInt BIGINT long setLong updateLong REAL float setFloat updateFloat FLOAT float setFloat updateFloat DOUBLE double setDouble updateDouble VARBINARY byte[ ] setBytes updateBytes BINARY byte[ ] setBytes updateBytes DATE java.sql.Date setDate updateDate TIME java.sql.Time setTime updateTime TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp CLOB java.sql.Clob setClob updateClob BLOB java.sql.Blob setBlob updateBlob 6|Page
  • 7. Tutorials Point, Simply Easy Learning ARRAY java.sql.Array setARRAY updateARRAY REF java.sql.Ref SetRef updateRef STRUCT java.sql.Struct SetStruct updateStruct JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to directly manipulate the respective data on the server. The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to a JDBC data type. ResultSet object provides corresponding getXXX() method for each data type to retrieve column value. Each method can be used with column name or by its ordinal position. SQL JDBC/Java setXXX getXXX VARCHAR java.lang.String setString getString CHAR java.lang.String setString getString LONGVARCHAR java.lang.String setString getString BIT boolean setBoolean getBoolean NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal TINYINT byte setByte getByte SMALLINT short setShort getShort INTEGER int setInt getInt BIGINT long setLong getLong REAL float setFloat getFloat FLOAT float setFloat getFloat DOUBLE double setDouble getDouble VARBINARY byte[ ] setBytes getBytes 7|Page
  • 8. Tutorials Point, Simply Easy Learning BINARY byte[ ] setBytes getBytes DATE java.sql.Date setDate getDate TIME java.sql.Time setTime getTime TIMESTAMP java.sql.Timestamp setTimestamp getTimestamp CLOB java.sql.Clob setClob getClob BLOB java.sql.Blob setBlob getBlob ARRAY java.sql.Array setARRAY getARRAY REF java.sql.Ref SetRef getRef STRUCT java.sql.Struct SetStruct getStruct JDBC - Create Database Example This tutorial provides an example on how to create a Database using JDBC application. Before executing following example, make sure you have the following in place:  You should have admin privilege to create a database in the given schema. To execute the following example you need to replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages . Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver . Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection . Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with datbase server. To create a new database, you need not to give any database name while preparing database URL as mentioned in the below example. 4. Execute a query . Requires using an object of type Statement for building and submitting an SQL statement to the database. 5. Clean up the environment . Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: 8|Page
  • 9. Tutorials Point, Simply Easy Learning Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; 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 database..."); stmt = conn.createStatement(); String sql = "CREATE DATABASE STUDENTS"; stmt.executeUpdate(sql); System.out.println("Database created successfully..."); }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 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 System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> 9|Page
  • 10. Tutorials Point, Simply Easy Learning When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to database... Creating database... Database created successfully... Goodbye! C:> JDBC - Select Database Example This tutorial provides an example on how to select a Database using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you need to replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages . Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver . Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection . Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database. Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database. 4. Clean up the environment . Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; try{ 10 | P a g e
  • 11. Tutorials Point, Simply Easy Learning //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); }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 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... Goodbye! C:> JDBC - Drop Database Example This tutorial provides an example on how to drop an existing Database using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you need to replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. NOTE: This is a serious operation and you have to make a firm decision before proceeding to delete a database because everything you have in your database would be lost. Required Steps: There are following steps required to create a new Database using JDBC application: 11 | P a g e
  • 12. Tutorials Point, Simply Easy Learning 1. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database. 4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to delete the database. 5. Clean up the environment . Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Deleting database..."); stmt = conn.createStatement(); String sql = "DROP DATABASE STUDENTS"; stmt.executeUpdate(sql); System.out.println("Database deleted successfully..."); }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 12 | P a g e
  • 13. Tutorials Point, Simply Easy Learning try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... Deleting database... Database deleted successfully... Goodbye! C:> JDBC - Create Tables Example This tutorial provides an example on how to create a table using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you can replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. 4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to create a table in a seleted database. 5. Clean up the environment . Requires explicitly closing all database resources versus relying on the JVM's garbage collection. 13 | P a g e
  • 14. Tutorials Point, Simply Easy Learning Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " + " first VARCHAR(255), " + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql); System.out.println("Created table in given database..."); }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 try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try 14 | P a g e
  • 15. Tutorials Point, Simply Easy Learning }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... Creating table in given database... Created table in given database... Goodbye! C:> JDBC - Drop Tables Example This tutorial provides an example on how to delete a table using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you can replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. NOTE: This is a serious operation and you have to make a firm decision before proceeding to delete a table because everything you have in your table would be lost. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. 4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to drop a table in a seleted database. 5. Clean up the environment . Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages 15 | P a g e
  • 16. Tutorials Point, Simply Easy Learning import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Deleting table in given database..."); stmt = conn.createStatement(); String sql = "DROP TABLE REGISTRATION "; stmt.executeUpdate(sql); System.out.println("Table deleted in given database..."); }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 try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> 16 | P a g e
  • 17. Tutorials Point, Simply Easy Learning When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... Deleting table in given database... Table deleted in given database... Goodbye! C:> JDBC - Insert Records Example This tutorial provides an example on how to insert records in a table using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you can replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. 4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table. 5. Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver 17 | P a g e
  • 18. Tutorials Point, Simply Easy Learning Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Inserting records into the table..."); stmt = conn.createStatement(); String sql = "INSERT INTO Registration " + "VALUES (100, 'Zara', 'Ali', 18)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES (101, 'Mahnaz', 'Fatma', 25)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES (102, 'Zaid', 'Khan', 30)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES(103, 'Sumit', 'Mittal', 28)"; stmt.executeUpdate(sql); System.out.println("Inserted records into the table..."); }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 try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... 18 | P a g e
  • 19. Tutorials Point, Simply Easy Learning Inserting records into the table... Inserted records into the table... Goodbye! C:> JDBC - Select Records Example This tutorial provides an example on how to select/ fetch records from a table using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you can replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. 4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to select (i.e. fetch ) records from a table. 5. Extract Data: Once SQL query is executed, you can fetch records from the table. 6. Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); 19 | P a g e
  • 20. Tutorials Point, Simply Easy Learning conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); //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"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.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 try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... Creating statement... 20 | P a g e
  • 21. Tutorials Point, Simply Easy Learning ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! C:> JDBC - Update Records Example This tutorial provides an example on how to update records in a table using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you can replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. 4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records. 5. Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); 21 | P a g e
  • 22. Tutorials Point, Simply Easy Learning //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql = "UPDATE Registration " + "SET age = 30 WHERE id in (100, 101)"; stmt.executeUpdate(sql); // Now you can extract all the records // to see the updated records sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); 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"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.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 try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample Now let us compile above example as follows: C:>javac JDBCExample.java C:> 22 | P a g e
  • 23. Tutorials Point, Simply Easy Learning When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... Creating statement... ID: 100, Age: 30, First: Zara, Last: Ali ID: 101, Age: 30, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! C:> JDBC - Delete Records Example This tutorial provides an example on how to delete records from a table using JDBC application. Before executing following example, make sure you have the following in place:  To execute the following example you can replace username and password with your actual user name and password.  Your MySQL or whatever database you are using is up and running. Required Steps: There are following steps required to create a new Database using JDBC application: 1. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. 2. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. 3. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. 4. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of WHERE clause to delete conditional records. 5. Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection. Sample Code: Copy and past following example in JDBCExample.java, compile and run as follows: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { 23 | P a g e
  • 24. Tutorials Point, Simply Easy Learning Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql = "DELETE FROM Registration " + "WHERE id = 101"; stmt.executeUpdate(sql); // Now you can extract all the records // to see the remaining records sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); 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"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.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 try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample 24 | P a g e
  • 25. Tutorials Point, Simply Easy Learning Now let us compile above example as follows: C:>javac JDBCExample.java C:> When you run JDBCExample, it produces following result: C:>java JDBCExample Connecting to a selected database... Connected database successfully... Creating statement... ID: 100, Age: 30, First: Zara, Last: Ali ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! C:> JDBC - Batch Processing: Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.  JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.  The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.  The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.  Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove. JDBC - Streaming Data: A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can hold large values, such as CLOB and BLOB data types. There are following methods which can be used to stream data: 1. setAsciiStream(): This method is used to supply large ASCII values. 2. setCharacterStream(): This method is used to supply large UNICODE values. 3. setBinaryStream(): This method is used to supply large binary values. The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream. Further Detail: 25 | P a g e
  • 26. Tutorials Point, Simply Easy Learning Refer to the link http://www.tutorialspoint.com/jdbc List of Tutorials from TutorialsPoint.com  Learn JSP  Learn ASP.Net  Learn Servlets  Learn HTML  Learn log4j  Learn HTML5  Learn iBATIS  Learn XHTML  Learn Java  Learn CSS  Learn JDBC  Learn HTTP  Java Examples  Learn JavaScript  Learn Best Practices  Learn jQuery  Learn Python  Learn Prototype  Learn Ruby  Learn script.aculo.us  Learn Ruby on Rails  Web Developer's Guide  Learn SQL  Learn RADIUS  Learn MySQL  Learn RSS  Learn AJAX  Learn SEO Techniques  Learn C Programming  Learn SOAP  Learn C++ Programming  Learn UDDI  Learn CGI with PERL  Learn Unix Sockets  Learn DLL  Learn Web Services  Learn ebXML  Learn XML-RPC  Learn Euphoria  Learn UML  Learn GDB Debugger  Learn UNIX  Learn Makefile  Learn WSDL  Learn Parrot  Learn i-Mode  Learn Perl Script  Learn GPRS  Learn PHP Script  Learn GSM  Learn Six Sigma  Learn WAP  Learn SEI CMMI  Learn WML  Learn WiMAX  Learn Wi-Fi  Learn Telecom Billing webmaster@TutorialsPoint.com 26 | P a g e
  • 27. Tutorials Point, Simply Easy Learning 27 | P a g e