Monday, March 26, 2007

Using XML as database with Java

here is how you can use XML file as a database,you can get the driver here

here is how you can connect to the database:

try {
// Load the DB2 JDBC Type 2 Driver with DriverManager
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}



Here is an example of XML as database
Import the package:

import com.ibm.db2.jcc.DB2Xml;

getting connection:

connection = DriverManager.getConnection(url, user, pass);

the prepare statement:

PreparedStatement stmt = connection.prepareStatement(sql);


Result Set:

option 1:
ResultSet resultSet = stmt.executeQuery();
option 2:
InputStream inputStream = resultSet.getBinaryStream(1);

option 3:
DB2Xml db2xml = (DB2Xml) resultSet.getObject(1);


Selecting a XML value:

String sql = "SELECT PID, DESCRIPTION from XMLPRODUCT where PID = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, "100-105-09");
ResultSet resultSet = stmt.executeQuery();
String xml = resultSet.getString("DESCRIPTION"); // or
InputStream inputStream = resultSet.getBinaryStream("DESCRIPTION"); // or
Reader reader = resultSet.getCharacterStream("DESCRIPTION"); // or
DB2Xml db2xml = (DB2Xml) resultSet.getObject("DESCRIPTION");

you can use other methods available in java

  • getString( )
  • getBinaryStream( )
  • getCharacterStrem( )
  • getObject( )
Inserting in XML file

String sql = "INSERT INTO xmlproduct VALUES(?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, "100-105-09");
File binFile = new File("productBinIn.xml");
InputStream inBin = new FileInputStream(xmlFile);
stmt.setBinaryStream(2, inBin, (int) binFile.getLength());
stmt.execute();



all you need is the db2 drivers you can find it here

https://www14.software.ibm.com/webapp/iwm/web/preLogin.do?lang=en_US&source=swg-dm-db2jdbcdriver


1 comment:

Anonymous said...

hi..
just wanna ask..do you know something bot j2ee ?
how to connect them with xml database ? need any dbms ? tq