JDBC Basics - Java Database Connectivity Steps
JDBC Basics - Java Database Connectivity Steps
by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote database access. You will learn how to create a table, insert values into it, query the table, retrieve results, and update the table with the help of a JDBC Program example. Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.
JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change database engines without changing database code.
other driver } catch(Exception x){ System.out.println( Unable to load the driver class! ); }
2. Creating a oracle jdbc Connection
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.
JDBC URL Example:: jdbc: <subprotocol>: <subname>Each driver has its own subprotocol Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
try{ Connection dbConnection=DriverManager.getConnection(url,loginName,Passwo rd) } catch( SQLException x ){ System.out.println( Couldnt get connection! ); }
3. Creating a jdbc Statement object,
Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method. Statement statement = dbConnection.createStatement(); A statement object is used to send and execute SQL statements to a database.
Statement: Execute simple sql queries without parameters. Statement createStatement() Creates an SQL Statement object. Prepared Statement: Execute precompiled sql queries with or without parameters. PreparedStatement prepareStatement(String sql) returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements. Callable Statement: Execute a call to a database stored procedure. CallableStatement prepareCall(String sql) returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements.
4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements: executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL statements and are executed with the method executeUpdate. execute() executes an SQL statement that is written as String object. ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results. ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.
Class driverObject = Class.forName(className); output.append(Driver : +driverObject+\n); output.append(Driver Installation Successful); JOptionPane.showMessageDialog(null, output); } catch (Exception e) { output = new StringBuffer(); output.append(Driver Installation FAILED\n); JOptionPane.showMessageDialog(null, output); System.out.println(Failed: Driver Error: + e.getMessage()); } } }
Download JDBC Sample Code
public class JDBCDriverInformation { static String userid=scott, password = tiger; static String url = jdbc:odbc:bob; static Connection con = null; public static void main(String[] args) throws Exception { Connection con = getOracleJDBCConnection(); if(con!= null){ System.out.println(Got Connection.); DatabaseMetaData meta = con.getMetaData(); System.out.println(Driver Name : +meta.getDriverName()); System.out.println(Driver Version : +meta.getDriverVersion()); }else{
System.out.println(Could not Get Connection); } } public static Connection getOracleJDBCConnection(){ try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); } catch(java.lang.ClassNotFoundException e) { System.err.print(ClassNotFoundException: ); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } return con; } }
----------------------------------------------------------------------------------------------------------------------------- -----------For this program code we have a class Jdbc Connection, We have a list of method required to connect and close the connection. Before the implementation of class we need to import a package java.sql.* needed for network interface between url and back end. Loading a driver is done by calling a class.forName ( ) and accept the driver class as argument. DriverManager.getConnection ( ) :This method returns you an connection object.DriverManager.getConnection built a connection with database. Using this method we establish a connection between url and database. Once the connection is built,println print the connection is created
con.close ( ) : An object of connection is used to close the connection between database and url. Finally the println print the connection is closed.In case there is an exception in try block, during the establishment of connection between the front end in java application(url) and backend. The catch block is responsible for handling the exception. JdbcConnection.java
import java.sql.*; public class JdbcConnection { public static void main(String args[]) { Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db = "komal"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root"; try { Class.forName(driver); con = DriverManager.getConnection(url + db, user, pass); System.out.println("jdbc driver for mysql : " + driver); System.out.println("Connection url : " + url + db); System.out.println("Connection is created..."); con.close(); System.out.println("Connection is closed..."); } catch (Exception e) { System.out.println(e); } } }