Java JDBC tutorial

Source: Internet
Author: User
Tags url example

The JDBC (Java database connectivity) API defines interfaces and classes for writing Database
Applications in Java 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
Create a table, insert values into it, query the table, retrieve results, and update the table
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 callthe JDBC library. JDBC loads a driver which talks to the database.
We can change database engines without changing database code.

JDBC basics-Java Database Connectivity steps

Before you can create a Java JDBC connection to the database, you must first import
Java. SQL package.

Import java. SQL. *; The Star (*) indicates that all of the classes in the package java. SQL are
To be imported.

1. loading a database driver,

In this step of the JDBC connection process, we load the driver class by calling class. forname ()
With the driver class name as an argument. Once loaded, the driver class creates an instance
Of itself. A client can connect to database server through JDBC driver. Since most of
Database servers support ODBC driver therefore JDBC-ODBC bridge driver is commonly used.
The return type of the class. forname (string classname) method is "class". Class is a class in
Java. lang package.

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Or any 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 provided 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 Syntax::    jdbc: <subprotocol>: <subname>

 

Jdbc url example: JDBC: <subprotocol >:< subname> • Each driver has its own subprotocol
• Each subprotocol has its own syntax for the source. We're using the jdbc odbc subprotocol, so the drivermanager knows to use the sun. JDBC. ODBC. jdbcodbcdriver.

try{  Connection dbConnection=DriverManager.getConnection(url,"loginName","Password")}catch( SQLException x ){System.out.println( "Couldn't 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.

Three kinds of statements

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.

ResultsetProvides 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.

ResultsetmetadataInterface holds information on the types and properties of the columns in
A resultset. It is constructed from the connection object.

 

Test JDBC Driver Installation

import javax.swing.JOptionPane;public class TestJDBCDriverInstallation_Oracle {   public static void main(String[] args) {  StringBuffer output  = new StringBuffer();  output.append("Testing oracle driver installation /n");  try {  String className = "sun.jdbc.odbc.JdbcOdbcDriver";  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

 

Java JDBC connection example, JDBC driver example

import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.SQLException;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;}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.