Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts

Java CLOB Example

SQL3 type is CLOB (Character Large OBject) for storing a large text in the character format. JDBC 2 introduced the interfaces java.sql.Blob and java.sql.Clob to support mapping for these new SQL types. JBDC 2 also added new methods, such as getBlob, setBinaryStream, getClob, setBlob, and setClob, in the interfaces ResultSet and PreparedStatement to access SQL.
CLOB : Reading

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery
    (“select clob_column from clob_table”);
while (rs.next())
{
CLOB blob = ((OracleResultSet)rs).getCLOB(1);
Reader reader = clob.getCharacterStream();
char [] buffer = new char[10];
int length = 0;
while ( (length  = reader.read (buffer)) != -1)
{
System.out.println (new String(buffer));
}
is.close();
}
CLOB : Writing
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery
  (“select clob_column from clob_table for update”);
while (rs.next())
{
  CLOB clob = ((OracleResultSet)rs).getCLOB(1);
   Writer writer = clob.getCharacterOutputStream();
   FileInputStream src = new FileInputStream(“tmp”);
   byte [] buffer = new byte[512];
   int read  = 0;
  while ( (read  = src.read(buffer)) != -1)
  {
     writer.write(buffer, 0, read);  // write clob.
  }
  src.close();
  writer.close();
}


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Java BLOB Example

Database can store not only numbers and strings, but also images. SQL3 introduced a new data type BLOB (Binary Large OBject) for storing binary data, which can be used to store images.
BLOB : Reading
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery
    (“select blob_column from blob_table”);
while (rs.next())
{
BLOB blob = ((OracleResultSet)rs).getBLOB(1);
InputStream is = blob.getBinaryStream();
int read =  0;
while ( (read  = is.read()) != -1)
{
// to do like writing a file using the stream
}
is.close();
}
BLOB : Writing
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery
  (“select blob_column from blob_table for update”);
while (rs.next())
{
BLOB blob = ((OracleResultSet)rs).getBLOB(1);
OutputStream os = blob.getBinaryOutputStream();
InputStream src = new InputStream(…);
byte [] buffer = new byte[1024];
int read  = 0;
while ( (read  = src.read(buffer)) != -1)
{
os.write(buffer, 0, read);  // write blob.
}
src.close();
os.close();
}

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Why do you use a data source object for a connection?

Data source object uses a logical name for a data source and this feature increases application portability. This removes the necessity of supplying information to each and every driver. Data source can be configured manually or automatically.

What is Java Transaction API?

Transaction :

Transaction is a complete unit of work that completes succesfully or results with unaltered state.

Java Transaction types:

Java Transaction Service(JTS) :
  • specifies the implementation of a Java transaction manager.
Java Transaction API(JTA) :
  • calls the lower-level JTS methods.
  • high level, implementation independent, protocol independent API.
  • offered by J2EE technology.
  • provides reliable environment for the J2EE container.
  • enables applications to perform distributed transactions.
  • specifies standard Java interfaces between a transaction manager and other components involved in a distributed transaction system. 
  • transaction manager, application, application server, and resource manager take roles in.
Transaction and Resource Managers :
  • Transaction manager decides whether to commit or rollback at the end of the transaction in a distributed system and coordinates various resource managers. 
  • Resource manager is responsible from the controlling of accessing the common resources in the distributed system.
JTA vs JDBC :
  • JDBC driver has to support both normal JDBC interactions and  XAResource part of JTA. 
  • XA protocol enables resource manager to take place in the transaction.
  • JDBC is responsible for "translating" between resource manager and transaction manager.
  • Application server, JDBC driver and  transaction manager care about the distributed transaction management. 
  • Application developer should not enter the scope of the transaction.
You might also like Following posts

Enable JDBC Logging

import java.net.URL;
import java.sql.*;


class JDBCapp  {
  static MyConnection theConn;


  public static void main (String args[]) {
    new JDBCapp().doit();
    }


  public void doit() {
    theConn = new MyConnection();
    theConn.connect("EAS Demo DB V3", "dba", "sql");


PreparedStatement prepstmt;
try {
  prepstmt = theConn.dbConn.prepareStatement
   ("SELECT emp_id FROM employee" );
  prepstmt.execute();
  prepstmt.close();
  }
catch (Exception e) { e.printStackTrace(); }
  theConn.disconnect();
  }
}




class MyConnection {
  Connection dbConn = null;
  void connect(String db, String user, String passw) {
    try {
      Driver d = 
       (Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
      String URL = "jdbc:odbc:" + db;
      dbConn = DriverManager.getConnection(URL, user, passw);
      java.io.PrintWriter w =
        new java.io.PrintWriter
           (new java.io.OutputStreamWriter(System.out));
      DriverManager.setLogWriter(w);
      }
    catch (Exception e) {
      e.printStackTrace();
      }
    }


  void disconnect() {
    try {
      dbConn.close();
      }
    catch (Exception e) {
      e.printStackTrace();
      }
    }
}

JDBC Program Using MySQL



    import java.sql.*;
    public class SampleMySQlProgram {
       public static void main(String[] args) {
        Connection conn = null; //Connection is use for connecting java and mysql
       Statement stmt = null; // use to execute mysql query into java app    String url = null;    try
    {

        //create connection
          Class.forName("com.mysql.jdbc.Driver");
        /*url =jdbc:mysql://<localhostname>:<portNumber>/databaseName*/       url = "jdbc:mysql://localhost:3306/databaseName";       conn = DriverManager.getConnection(url,"root",""); 
        /* if you are using another user change (url,"root","")  into (url"username","yourpassword")*/ 
           stmt = conn.createStatement();
         
        //execute mysql query in this example i just use insert       stmt.executeUpdate("insert into tbltest(id,name)values('001','userAccount')");      
       // get record from mysql and display it.       ResultSet dsply = stmt.executeQuery("select * from tbltest");
        //loops until ther is no next from record.
         while(dsply.next()){
              int IDNO = dsply.getInt("ID"); //get record from ID field           String Name = dsply.getString("Name"); //get record from Name field           System.out.print(" IDNO: "+IDNO); // display ID           System.out.print(" Name: "+Name); //display Name           System.out.println(); //print next line       }    }catch(Exception e){
          e.printStackTrace();
       }  } }

CallableStatement Example in Java


The JDBC CallableStatement interface extends PreparedStatement and provides support for output and input/output parameters. The CallableStatement interface also has support for input parameters that is provided by the PreparedStatement interface.
The CallableStatement interface allows the use of SQL statements to call stored procedures. Stored procedures are programs that have a database interface. These programs possess the following:
  • They can have input and output parameters, or parameters that are both input and output.
  • They can have a return value.
  • They have the ability to return multiple ResultSets.

    CREATE PROCEDURE GetImmediateManager
       @employeeID INT,
       @managerID INT OUTPUT
    AS
    BEGIN
       SELECT @managerID = ManagerID 
       FROM HumanResources.Employee 
       WHERE EmployeeID = @employeeID
    END
Conceptually in JDBC, a stored procedure call is a single call to the database, but the program associated with the stored procedure may process hundreds of database requests. The stored procedure program may also perform a number of other programmatic tasks not typically done with SQL statements.

    public static void executeStoredProcedure(
    Connection con) {
       try {
          CallableStatement cstmt = con.prepareCall("{call dbo.GetImmediateManager(?, ?)}");
          cstmt.setInt(1, 5);
          cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
          cstmt.execute();
          System.out.println("MANAGER ID: " + cstmt.getInt(2));
       }
       catch (Exception e) {
          e.printStackTrace();
       }
    }

JDBC Transaction Management


The database management system manage the database over multiple environment in which there may be multiple users working. So there may be chances of data loss over multiple environment as well by the users. Therefore to overcome such problems, the DBMS provides a mechanism to maintain data integrity within the DBMS. Transactions are used to provide the data integrity over multiple users.
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails.
JDBC enables you to manage transactions by manipulating the Connection object’ssetAutoCommit() and using its rollback() method, which undoes all changes, up to the last commit. Remember that bu default all the queries you executed is commeted. To use the transaction benifits first set the auto-commit as false by callingsetAutoCommet(false) method of Connection interface.


package com.JavaStuff.jdbc;


import java.sql.*;
import java.util.*;
import java.io.*;
/**
 * @author Javastuff
 */
public class TransactionsExample {


public static void main(String s[]) throws Exception {


Driver d= (Driver) ( Class.forName( 
"oracle.jdbc.driver.OracleDriver").newInstance());


Properties p=new Properties ();
p.put("user","scott");
p.put("password","tiger");


Connection con=d.connect("jdbc:oracle:thin:@mysys:1521:javastuff",p);


con.setAutoCommit(false);


String srcaccno=s[0];
String destaccno=s[1];


PreparedStatement ps= con.prepareStatement("update bank set bal=bal+? where accno=?");


ps.setDouble(1,500);
ps.setString(2,destaccno);


int i=ps.executeUpdate();


ps.setDouble(1,-500);
ps.setString(2,srcaccno);


int j=ps.executeUpdate();


if (i==1&&j==1){
con.commit();
System.out.println("Amount transfered");
con.close();
return;
}
con.rollback();
System.out.println("Cannot transfer the amount");
con.close();
}//main
}//class


Get CLOB Object Using JDBC


package com.Javastuff.jdbc;


import java.sql.*;
import java.util.*;
import java.io.*;
/**
 * @author Javastuff
 */
public class GetEmployeeDetails {

public static void main(String s[]) throws Exception {


Driver d= (Driver) ( Class.forName( 
"oracle.jdbc.driver.OracleDriver").newInstance());


Properties p=new Properties ();
p.put("user","scott");
p.put("password","tiger");


Connection con=d.connect(
"jdbc:oracle:thin:@mysys:1521:javastuff",p);


Statement st=con.createStatement();
ResultSet rs=st.executeQuery( "select profile from empprofiles where empno="+s[0]);


while (rs.next()) {
Reader r=rs.getCharacterStream(1);


FileWriter fw=new FileWriter("ProfileOf"+s[0]+".doc");


int i=r.read();
while (i!=-1){
fw.write(i);
i=r.read();
}//while


}//while
System.out.println("Profile retrived");
con.close();
}//main
}//class

CLOB Examples Using JDBC


The examples that follow will explain how to:
  1. Inserting and retrieving empty CLOB data.Use 
  2. Retrieve CLOB data using the Ingres JDBC driver.
  3. Updating existing CLOB data.

Inserting and retrieving empty CLOB data:


conn = getConnection();
  prepStmt = conn.prepareStatement("INSERT INTO clob_table VALUES(?,?,?,?)");
  prepStmt.setString(1,id);
  prepStmt.setString(2,filename);
  // Insert empty CLOB data
  prepStmt.setString(3, "");
  prepStmt.setString(4, "2009-07-10");	
  prepStmt.execute();

Use various techniques to insert CLOB data:


Clob c = rs.getClob(columnIndex);
  InputStream data =  c.getAsciiStream();

Updating existing CLOB data:

public static void updateClobAsString(String id, String content) {
     Connection conn = null;
     PreparedStatement prepStmt = null;
     ResultSet rs = null;
     try {
        //Obtains a connection
        conn = getConnection();
        prepStmt = conn.prepareStatement("UPDATE clob_table SET xmldocument = ? WHERE id='" + id + "'");
        prepStmt.setString(1,content);
        prepStmt.execute();
     } 
     catch(Exception sqlEx) {
        sqlEx.printStackTrace();
     }
     finally {
        DbUtils.closeQuietly(conn, prepStmt, rs);
     }
  }

CLOB Datatype in Java


Clob object represents the Java programming language mapping of an SQL CLOB (Character Large Object). An SQL CLOB is a built-in type that stores a Character Large Object as a column value in a row of a database table. Methods in the interfaces ResultSetCallableStatement, and PreparedStatement allow a programmer to access the SQL3 type CLOB in the same way that more basic SQL types are accessed. In other words, an application using the JDBC 2.0 API uses methods such as getClob and setClob for a CLOB value the same way it uses getInt and setInt for an INTEGER value or getString andsetString for a CHAR or VARCHAR value.
The default is for a JDBC driver to implement the Clob interface using the SQL type LOCATOR(CLOB) behind the scenes. A LOCATOR(CLOB) designates an SQLCLOB residing on a database server, and operations on the locator achieve the same results as operations on the CLOB itself. This means that a client can operate on aClob instance without ever having to materialize the CLOB data on the client machine. The driver uses LOCATOR(CLOB) behind the scenes, making its use completely transparent to the JDBC programmer.
The standard behavior for a Clob instance is to remain valid until the transaction in which it was created is either committed or rolled back.
The interface Clob provides methods for getting the length of an SQL CLOB value, for materializing the data in a CLOB value on the client, and for searching for a substring or CLOB object within a CLOB value.


Creating a Clob Object
The following code fragment illustrates creating a Clob object, where rs is a ResultSet object:
Clob clob = rs.getClob(1);
The variable clob can now be used to operate on the CLOB value that is stored in the first column of the result set rs.

Materializing Clob Data

Programmers can invoke methods in the JDBC API on a Clob object as if they were operating on the SQL CLOB value it designates. However, if they want to operate on a Clob object as an object in the Java programming language, they must first materialize the data of the CLOB object on the client. The Clob interface provides three methods for materializing a Clob object as an object in the Java programming language:
  • getAsciiStream materializes the CLOB value as a byte stream containing Ascii bytes
Clob notes = rs.getClob("NOTES");
java.io.InputStream in = notes.getAsciiStream();
byte b = in.read();
// in contains the characters in the CLOB value designated by
// notes as Ascii bytes; b contains the first character as an Ascii 
// byte
  • getCharacterStream materializes the CLOB value as a stream of Unicode characters
java.io.Reader reader = notes.getCharacterStream();
int c = Reader.read();
// c contains the first character in the CLOB that notes designates
  • getSubString materializes all or part of the CLOB value as a String object
String substring = notes.getSubString(10, 5);
// substring contains five characters, starting with the tenth
// character of the CLOB value that notes designates
long len = notes.length();
String substring = notes.getSubString(1, len);
// substring contains all of the characters in the CLOB object that
// notes designates

Storing a Clob Object

To store a Clob object in the database, it is passed as a parameter to the PreparedStatement method setClob. For example, the following code fragment stores the Clob object notes by passing it as the first input parameter to the PreparedStatement object pstmt:
Clob notes = rs.getClob("NOTES");
PreparedStatement pstmt = con.prepareStatement(
	"UPDATE SALES_STATS SET COMMENTS = ? WHERE SALES > 500000");
pstmt.setClob(1, notes);
pstmt.executeUpdate(); 
The CLOB value designated by notes is now stored in the table SALES_STATS in column COMMENTS in every row where the value in the column SALES is greater than 500000.


Clob Interface Definition


  1. long length() throws SQLException;
  2. InputStream getAsciiStream() throws SQLException;
  3. Reader getCharacterStream() throws SQLException;
  4. String getSubString(long pos, int length) throws SQLException;
  5. long position(String searchstr, long start) throws SQLException;
  6. long position(Clob searchstr, long start) throws SQLException;

How to convert blob to byte array in java


ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];

InputStream in = blob.getBinaryStream();

int n = 0;
while ((n=in.read(buf))>=0)
{
   baos.write(buf, 0, n);

}

in.close();
byte[] bytes = baos.toByteArray(); 

Read BLOBs data from database



import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;

public class BlobReadDemo {
    private static String url = "jdbc:oracle:thin:@localhost:1521:xe";
    private static String username = "Javastuff";
    private static String password = "welcome";

    public static void main(String[] args) throws Exception {
        Connection conn = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection(url, username, password);

            String sql = "SELECT name, description, image FROM pictures ";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString(1);
                System.out.println("Name        = " + name);
                String description = resultSet.getString(2);
                System.out.println("Description = " + description);

                File image = new File("D:\\java.gif");
                FileOutputStream fos = new FileOutputStream(image);

                byte[] buffer = new byte[256];

                //
                // Get the binary stream of our BLOB data
                //
                InputStream is = resultSet.getBinaryStream(3);
                while (is.read(buffer) > 0) {
                    fos.write(buffer);
                }

                fos.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        }
    }
}

Inser a BLOB object in Java


import java.sql.*;
import java.util.*;
import java.io.*;


public class InsertBlobExample {
public static void main(String s[]) throws Exception {


Driver d= (Driver) ( Class.forName( 
"oracle.jdbc.driver.OracleDriver").newInstance());


Properties p=new Properties ();
p.put("user","scott");
p.put("password","tiger");


Connection con=d.connect(
"jdbc:oracle:thin:@mysys:1521:Javastuff",p);


PreparedStatement ps= con.prepareStatement(
"insert into personaldetails(empno,photo) values(?,?)");


ps.setInt(1,Integer.parseInt(s[0]));
File f=new File("MyImage.jpg");
FileInputStream fis= new FileInputStream(f);
ps.setBinaryStream(2,fis, (int)f.length());
int i=ps.executeUpdate();
System.out.println("Record inserted successfully , count : "+i);
con.close();
}//main
}//class

Blob in JDBC


Blob object represents the Java programming language mapping of an SQL BLOB (Binary Large Object). An SQL BLOB is a built-in type that stores a Binary Large Object as a column value in a row of a database table. Methods in the interfaces ResultSetCallableStatementand PreparedStatement allow a programmer to access the SQL3 type BLOB in the same way that SQL92 built-in types are accessed. In other words, an application using the JDBC 2.0 API uses methods such as getBlob and setBlob for a BLOB value the same way it uses getInt and setInt for an INTEGER value or getString and setString for aCHAR or VARCHAR value.
In a standard implementation, a JDBC driver implements the Blob interface using the SQL type LOCATOR(BLOB) behind the scenes. A LOCATOR(BLOB) designates an SQL BLOB value residing on a database server, and operations on the locator achieve the same results as operations on the BLOB value itself. This means that a client can operate on a Blob instance without ever having to materialize the BLOB data on the client machine, which can improve performance significantly. Because the driver uses LOCATOR(BLOB) behind the scenes, its use is completely transparent to the programmer using a JDBC driver.
The standard behavior for a Blob instance is to remain valid until the transaction in which it was created is either committed or rolled back.
The Blob interface provides methods for getting the length of an SQL BLOB value, for materializing a BLOB value on the client, and for determining the position of a pattern of bytes within a BLOB value.


Creating a Blob ObjectThe following code fragment illustrates creating a Blob object, where stmt is a Statement object:

ResultSet rs = stmt.executeQuery("SELECT DATA FROM TABLE1");
rs.first();
Blob data = rs.getBlob("DATA");
The variable blob contains a logical pointer to the BLOB value that is stored in the column DATA in the first row of the result set rs. It does not contain the data in theBLOB value, but as far as JDBC methods are concerned, it is operated on as if it did.

Storing a Blob Object

To store a Blob object in the database, it is passed as a parameter to the PreparedStatement method setBlob. For example, the following code fragment stores the Blob object stats by passing it as the first input parameter to the PreparedStatement object pstmt:

Blob stats = rs.getBlob("STATS");
PreparedStatement pstmt = con.prepareStatement(
	"UPDATE SIGHTINGS SET MEAS = ? WHERE AREA = 'NE'");
pstmt.setBlob(1, stats);
pstmt.executeUpdate();

Blob Methods:

  1. long length() throws SQLException;
  2. InputStream getBinaryStream() throws SQLException;
  3. byte[] getBytes(long pos, int length) throws SQLException;
  4. long position(byte [] pattern, long start) throws SQLException; 
  5. long position(Blob pattern, long start) throws SQLException;
Examples:
1. Insert a BLOB data into Database
2. Read BLOBs data from Database

BatchUpdate in JDBC




The JDBC drivers that support JDBC 2.0 and above support batch updates. Batch updates is a option given by the JDBC in which application developers can submit a set of SQL update statements as batch to the database.
The following methods used for creating, executing, and removing a batch of SQL updates: 



1. addBatch
2. executeBatch
3. clearBatch 



package com.javstuff.jdbc;


import java.sql.*;
import java.util.*;
import java.io.*;
/**
 * @author Javastuff
 */
public class BatchUpdateExample {


public static void main(String s[]) throws Exception {


Driver d= (Driver) ( Class.forName( 
"oracle.jdbc.driver.OracleDriver").newInstance());


Properties p=new Properties ();
p.put("user","scott");
p.put("password","tiger");


Connection con=d.connect("jdbc:oracle:thin:@mysys:1521:javastuff",p);


Statement st=con.createStatement();
//statement1
st.addBatch("insert into emp(empno,sal,deptno) values("+s[0]+",1000,10)");
//statement2
st.addBatch("update emp set sal=2000 where empno="+s[0]);
//statement3
st.addBatch("insert into emp(empno,sal,deptno) values(202,1000,10)");
//statement4
st.addBatch("insert into emp(empno,sal,deptno) values(203,1000,10)");




try {
int[] counts=st.executeBatch();
System.out.println("Batch Executed Successfully");
for (int i=0;i<counts.length;i++){
System.out.println("Number of records effected by statement"+(i+1)+": "+counts[i]);
}//for
}//try
catch(BatchUpdateException e){
System.out.println("Batch terminated with an abnormal condition");


int[] counts=e.getUpdateCounts();
System.out.println("Batch terminated at statement"+ (counts.length+1));


for (int i=0;i<counts.length;i++) {
System.out.println("Number of records effected by the statement"+ (i+1)+": "+counts[i]);
}//for
}//catch
con.close();
}//main
}//class

Arrays in JDBC


lArray, one of the SQL 99 datatypes. offers you the facility to include an ordered list of values within the column. The java.sql.Array interface to store the values of the array types. To store the Array first we need to create a User-Defined-Type Array. this can be done by creating a UDT as array in database.



package com.Javastuff.jdbc;

import java.sql.*;
import java.util.*;
import oracle.sql.*;
/**
 * @author Javastuff
 */
public class InsertEmpPassportDetails {
public static void main(String s[]) throws Exception {

Driver d= (Driver) ( Class.forName( 
"oracle.jdbc.driver.OracleDriver").newInstance());

Properties p=new Properties ();
p.put("user","scott");
p.put("password","tiger");

Connection con=d.connect(
"jdbc:oracle:thin:@Javastuff:1521:sandb",p);

PreparedStatement ps=con.prepareStatement("insert into emppassportDetails values(?,?,?)");

ps.setInt(1,7934);
ps.setString(2,"12345A134");
String s1[]={"v1","v2","v3","v4","v5"};

ArrayDescriptor ad=ArrayDescriptor.createDescriptor("VISA_NOS",con);

ARRAY a=new ARRAY(ad,con,s1);

ps.setArray(3,a);

int i=ps.executeUpdate();
System.out.println("Row Inserted, count : "+i);
con.close();
}//main
}//class

DatabaseMetaData in JDBC

The DatabaseMetaData class is used to determine the capabilities of a JDBC driver and it database during runtime. If a given method of this interface is not supported by the JDBC driver, the method will either throw an SQLException, or in the case of a method that returns a result set, it may return null. Some of the methods take search patterns as its arguments. The pattern values used can be the SQL wildcard characters % and _. Other search arguments accept an empty set ("") when the argument is not applicable, or null to drop the argument from the search criteria.


  This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC driver that is used with it. Different relational DBMSs often support different features, implement features in different ways, and use different data types. In addition, a driver may implement a feature on top of what the DBMS offers. Information returned by methods in this interface applies to the capabilities of a particular driver and a particular DBMS working together.
The JDBC API enables you to uncover metadata about a database using the DatabaseMetaData interfaces. The DatabaseMetaData interface enables you to obtain information about your database's attributes and make runtime decisions based around that information.
package com.javastuff.jdbc;
import java.sql.*;
import java.util.*;
import java.io.*;
public class DataBaseMetaDataExample {
public static void main(String s[]) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:javastuff", "scott","tiger");

DatabaseMetaData db= con.getMetaData();
System.out.println("Database name : "+db.getDatabaseProductName());
System.out.println("Database version : "+db.getDatabaseProductVersion());
System.out.println("\nDriver Name : "+ db.getDriverName());
System.out.println("Driver Version : "+ db.getDriverVersion());
con.close();
}//main
}//class

Note :To execute the following example you can replace username and password with your actual user name and password.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email