A ResultSet cursor is initially positioned before the first row;
the first call to the method next makes the first row the current row;
the second call makes the second row the current row, and so on.
If an input stream is open for the current row, a call to the method next will implicitly close it.
A ResultSet object's warning chain is cleared when a new row is read.
Returns: true if the new current row is valid; false if there are no more rows
Throws: SQLException if a database access error occurs
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Thursday, July 31, 2008
smple prgram to read from console in java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
public class ReadDoubleFromConsole {
public static void main(String[] args) {
System.out.println("Enter a number.");
double numberFromConsole;
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
DecimalFormat df = new DecimalFormat();
Number n = df.parse(s);
numberFromConsole = n.doubleValue();
} catch (IOException e) {
numberFromConsole = 0;
} catch (ParseException e) {
numberFromConsole = 0;
}
System.out.println(numberFromConsole );
}
}
Wednesday, July 30, 2008
sample program to opoen open office spread sheet from Java
//package SpreadSheetAPI;
import com.sun.star.beans.PropertyValue;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNamed;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sheet.XCellRangeAddressable;
import com.sun.star.sheet.XSheetCellCursor;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XUsedAreaCursor;
import com.sun.star.table.CellRangeAddress;
import com.sun.star.table.XCell;
import com.sun.star.text.XText;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import spreadsheetUtilities.*;
/**
* A Sample for access xls/ods from OOo API
* Requirement:
* 1.Install OOo 2.0
* 2.Add jars to your project.(In OOoInstallPath\program\classes)
* at least those jars must be included : juh.jar,jurt.jar,ridl.jar,unoil.jar
*
**/
public class ReadSheetCellsSample {
private XComponentContext xRemoteContext = null;
private XMultiComponentFactory xRemoteServiceManager = null;
public ReadSheetCellsSample() {
}
public static void main(String[] args) {
ReadSheetCellsSample helloTextTableShape1 = new ReadSheetCellsSample();
try {
helloTextTableShape1.outSheets();
} catch (java.lang.Exception e) {
e.printStackTrace();
} finally {
System.out.println("...End");
System.exit(0);
}
}
protected void outSheets() throws java.lang.Exception {
// xls,service
XComponent xCalcComponent = loadComponent("D:\\Temp\\sample.ods");
XSpreadsheetDocument xSpreadsheetDocument = (XSpreadsheetDocument) UnoRuntime
.queryInterface(XSpreadsheetDocument.class, xCalcComponent);
com.sun.star.sheet.XSpreadsheets xSheets = xSpreadsheetDocument.getSheets();
// XIndexAccesssheet
XIndexAccess xIndexedSheets = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xSheets);
int sheetCount = xIndexedSheets.getCount();
System.out.println("Sheet Count:" + sheetCount);
for (int i = 0; i < sheetCount; i++) {
Object sheet = xIndexedSheets.getByIndex(i);
XSpreadsheet xSheet = (XSpreadsheet) UnoRuntime.queryInterface(
XSpreadsheet.class, sheet);
// XNamedSheet
XNamed xSheetName = (XNamed) UnoRuntime.queryInterface(
XNamed.class, sheet);
System.out.println("Sheet " + i + ":" + xSheetName.getName());
outSheet(xSheet);
}
//To wait in the application..
//wait(5000);
//CalctryCalcsoffice.bin?soffice.exe
//xCalcComponent.dispose();
}
protected void outSheet(XSpreadsheet xSheet) throws Exception {
//Cursor
XSheetCellCursor xCursor = xSheet.createCursor();
// XUsedAreaCursor,
XUsedAreaCursor xUsedCursor = (XUsedAreaCursor) UnoRuntime
.queryInterface(XUsedAreaCursor.class, xCursor);
xUsedCursor.gotoStartOfUsedArea(false);
xUsedCursor.gotoEndOfUsedArea(true);
XCellRangeAddressable xSheetRange = (XCellRangeAddressable) UnoRuntime
.queryInterface(XCellRangeAddressable.class, xCursor);
CellRangeAddress cellRangeAddress = xSheetRange.getRangeAddress();
System.out.println(cellRangeAddress.StartRow);
System.out.println(cellRangeAddress.StartColumn);
System.out.println(cellRangeAddress.EndRow);
System.out.println(cellRangeAddress.EndColumn);
int rowCount = cellRangeAddress.EndRow + 1;
int colCount = cellRangeAddress.EndColumn + 1;
System.out.println("row count:" + rowCount + ",column count" + colCount);
for (int row = 0; row < rowCount; row++) {
for (int col = 0; col < colCount; col++) {
System.out.println("Column : "+ col + " Row : "+row);
XCell cell = xCursor.getCellByPosition(col, row);
String formula = cell.getFormula();
XText xText = (XText) UnoRuntime.queryInterface(XText.class,
cell);
String text = xText.getString();
System.out.println("\t" + row + "," + col + "," + formula + ","
+ text);
cell.setValue(219);
cell.setFormula("=sum(A1,A2)");
}
}
}
protected XComponent loadComponent(String filePath)
throws java.lang.Exception {
String loadUrl = "file:///" + filePath;
xRemoteServiceManager = this.getRemoteServiceManager();
Object desktop = xRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", xRemoteContext);
XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime
.queryInterface(XComponentLoader.class, desktop);
PropertyValue[] loadProps = new PropertyValue[3];
loadProps[0] = new PropertyValue();
loadProps[0].Name = "ReadOnly";
loadProps[0].Value = new Boolean(true);
loadProps[1] = new PropertyValue();
loadProps[1].Name = "DocumentTitle";
loadProps[1].Value = "PMGUI Report";
//Default all macros will be Run...
loadProps[2] = new PropertyValue();
loadProps[2].Name = "MacroExecutionMode";
loadProps[2].Value = 4;
//loadProps[2] = new PropertyValue();
//loadProps[2].Name = "Hidden";
//loadProps[2].Value = new Boolean(true);
//loadProps[1] = new PropertyValue();
//loadProps[1].Name = "FilterName";
//loadProps[1].Value = "writer_pdf_Export";
return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0,loadProps);
}
protected XMultiComponentFactory getRemoteServiceManager()
throws java.lang.Exception {
if (xRemoteContext == null && xRemoteServiceManager == null) {
try {
// First step: get the remote office component context
xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");
xRemoteServiceManager = xRemoteContext.getServiceManager();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
return xRemoteServiceManager;
}
}
import com.sun.star.beans.PropertyValue;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNamed;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sheet.XCellRangeAddressable;
import com.sun.star.sheet.XSheetCellCursor;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XUsedAreaCursor;
import com.sun.star.table.CellRangeAddress;
import com.sun.star.table.XCell;
import com.sun.star.text.XText;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import spreadsheetUtilities.*;
/**
* A Sample for access xls/ods from OOo API
* Requirement:
* 1.Install OOo 2.0
* 2.Add jars to your project.(In OOoInstallPath\program\classes)
* at least those jars must be included : juh.jar,jurt.jar,ridl.jar,unoil.jar
*
**/
public class ReadSheetCellsSample {
private XComponentContext xRemoteContext = null;
private XMultiComponentFactory xRemoteServiceManager = null;
public ReadSheetCellsSample() {
}
public static void main(String[] args) {
ReadSheetCellsSample helloTextTableShape1 = new ReadSheetCellsSample();
try {
helloTextTableShape1.outSheets();
} catch (java.lang.Exception e) {
e.printStackTrace();
} finally {
System.out.println("...End");
System.exit(0);
}
}
protected void outSheets() throws java.lang.Exception {
// xls,service
XComponent xCalcComponent = loadComponent("D:\\Temp\\sample.ods");
XSpreadsheetDocument xSpreadsheetDocument = (XSpreadsheetDocument) UnoRuntime
.queryInterface(XSpreadsheetDocument.class, xCalcComponent);
com.sun.star.sheet.XSpreadsheets xSheets = xSpreadsheetDocument.getSheets();
// XIndexAccesssheet
XIndexAccess xIndexedSheets = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xSheets);
int sheetCount = xIndexedSheets.getCount();
System.out.println("Sheet Count:" + sheetCount);
for (int i = 0; i < sheetCount; i++) {
Object sheet = xIndexedSheets.getByIndex(i);
XSpreadsheet xSheet = (XSpreadsheet) UnoRuntime.queryInterface(
XSpreadsheet.class, sheet);
// XNamedSheet
XNamed xSheetName = (XNamed) UnoRuntime.queryInterface(
XNamed.class, sheet);
System.out.println("Sheet " + i + ":" + xSheetName.getName());
outSheet(xSheet);
}
//To wait in the application..
//wait(5000);
//CalctryCalcsoffice.bin?soffice.exe
//xCalcComponent.dispose();
}
protected void outSheet(XSpreadsheet xSheet) throws Exception {
//Cursor
XSheetCellCursor xCursor = xSheet.createCursor();
// XUsedAreaCursor,
XUsedAreaCursor xUsedCursor = (XUsedAreaCursor) UnoRuntime
.queryInterface(XUsedAreaCursor.class, xCursor);
xUsedCursor.gotoStartOfUsedArea(false);
xUsedCursor.gotoEndOfUsedArea(true);
XCellRangeAddressable xSheetRange = (XCellRangeAddressable) UnoRuntime
.queryInterface(XCellRangeAddressable.class, xCursor);
CellRangeAddress cellRangeAddress = xSheetRange.getRangeAddress();
System.out.println(cellRangeAddress.StartRow);
System.out.println(cellRangeAddress.StartColumn);
System.out.println(cellRangeAddress.EndRow);
System.out.println(cellRangeAddress.EndColumn);
int rowCount = cellRangeAddress.EndRow + 1;
int colCount = cellRangeAddress.EndColumn + 1;
System.out.println("row count:" + rowCount + ",column count" + colCount);
for (int row = 0; row < rowCount; row++) {
for (int col = 0; col < colCount; col++) {
System.out.println("Column : "+ col + " Row : "+row);
XCell cell = xCursor.getCellByPosition(col, row);
String formula = cell.getFormula();
XText xText = (XText) UnoRuntime.queryInterface(XText.class,
cell);
String text = xText.getString();
System.out.println("\t" + row + "," + col + "," + formula + ","
+ text);
cell.setValue(219);
cell.setFormula("=sum(A1,A2)");
}
}
}
protected XComponent loadComponent(String filePath)
throws java.lang.Exception {
String loadUrl = "file:///" + filePath;
xRemoteServiceManager = this.getRemoteServiceManager();
Object desktop = xRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", xRemoteContext);
XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime
.queryInterface(XComponentLoader.class, desktop);
PropertyValue[] loadProps = new PropertyValue[3];
loadProps[0] = new PropertyValue();
loadProps[0].Name = "ReadOnly";
loadProps[0].Value = new Boolean(true);
loadProps[1] = new PropertyValue();
loadProps[1].Name = "DocumentTitle";
loadProps[1].Value = "PMGUI Report";
//Default all macros will be Run...
loadProps[2] = new PropertyValue();
loadProps[2].Name = "MacroExecutionMode";
loadProps[2].Value = 4;
//loadProps[2] = new PropertyValue();
//loadProps[2].Name = "Hidden";
//loadProps[2].Value = new Boolean(true);
//loadProps[1] = new PropertyValue();
//loadProps[1].Name = "FilterName";
//loadProps[1].Value = "writer_pdf_Export";
return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0,loadProps);
}
protected XMultiComponentFactory getRemoteServiceManager()
throws java.lang.Exception {
if (xRemoteContext == null && xRemoteServiceManager == null) {
try {
// First step: get the remote office component context
xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");
xRemoteServiceManager = xRemoteContext.getServiceManager();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
return xRemoteServiceManager;
}
}
JDBC connectivity to informix
To Run A JDBC program , following steps should be followed
1. Install the appropriate JDBC libraries according to ur Operating System/System configuration
2. Need to finalize the URL to connect to the Database
3. need to include the Directory of the JDBC library to the "CLASSPATH" environment varaiable.
4. Run the Program.
We can get appropriate JDBC driver from different Vendors.. following link will give the Details about the which Driver to Choose and all
http://developers.sun.com/product/jdbc/drivers
Download the appropriate Driver and install.
The main thing in running a JDBC program is deciding the Conncetion URL.
The URL string looks like this:
"jdbc:informix-sqli://hostname:port_num/database_name:informixserver=server;user=user;password=pwd"
where jdbc is the main protocol and informix-sqli is the sub protocol
and all other fields are self explanatory
example link :
jdbc:informix-sqli://scsibox:1526/my_data:informixserver=ol_scsibox;user=informix;password=Informix
use the Driver name as "com.informix.jdbc.IfxDriver"
so remaining all we can find from SUN help... i.e.. different classess and all..
one sample program:
import java.sql.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import sqlj.runtime.ref.DefaultContext;
public class ConnectionManager
{
String DRIVER = null ; //JDBC Driver class
String DBURL = null ; //Database URL
String PWD = null, UID = null ; //Password for database account
DefaultContext ctx;
Statement stmt;
public Connection conn;
public Driver d;
String Query = null;
ResultSet rs = null;
int rc = -1;
//This block has to be changed and ConnectionManager.java recompiled
//Assign Default values for Driver loading...
public ConnectionManager(){
DRIVER = "com.informix.jdbc.IfxDriver";
DBURL = "jdbc:informix-sqli://10.128.96.66:5030/omcdb:informixserver=omc_sys1;"+
"username=informix;password=informix";
UID = "informix";
PWD = "informix";
//Establish connection
newConnection();
}
public ConnectionManager(String sDriver, String sDBUrl,String sUID,String sPWD){
DRIVER = sDriver;
DBURL = sDBUrl;
UID = sUID;
PWD = sPWD;
//Establish connection
newConnection();
}
public void newConnection()
{
try
{
d = (Driver)(Class.forName( DRIVER ).newInstance());
DriverManager.registerDriver(d);
System.out.println("Informix Driver Successfully Created....");
}
catch (Exception e)
{
System.err.println( "Could not load driver: " + DRIVER ) ;
System.err.println(e) ;
System.exit(1) ;
}
try
{
conn = DriverManager.getConnection (DBURL, UID, PWD);
//conn.setAutoCommit(false); // Turn AutoCommit off
System.out.println("Created Connection successfully to the Database");
}
catch (SQLException exception)
{
System.out.println("Error: could not get a connection");
System.err.println(exception) ;
exception.printStackTrace();
System.exit(1);
}
}
public void setSQLQuery(String query){
Query = query;
}
//This Method is only to execute statments which dont return Result set...
public int executeQuery(){
rc = -1;
try{
stmt = conn.createStatement();
rc = stmt.executeUpdate(Query);
System.out.println("Transaction successful .. Updated Rows : " + rc);
}catch(SQLException e){
System.out.println("FAILED: execution failed - statement: " + Query);
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
try{
stmt.close();
}catch(SQLException e){
}
return rc;
}
//This shoulb be used with select like queries... which result Resultset...
public ResultSet fetchResultset(){
rs = null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(Query);
System.out.println("Fetched Result Set Successfully");
}catch(SQLException e){
System.out.println("FAILED: execution failed - statement: " + Query);
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
try{
stmt.close();
}catch(SQLException e){
}
return rs;
}
public void closeResultset(){
try{
rs.close();
rs = null;
}catch(SQLException e){
}
}
public DefaultContext initContext(){
ctx = DefaultContext.getDefaultContext();
if (ctx == null) {
try {
newConnection();
ctx = new DefaultContext(conn);
}
catch (SQLException e) {
System.out.println("Error: could not get a default context");
System.err.println(e) ;
System.exit(1);
}
DefaultContext.setDefaultContext(ctx);
}
return ctx;
}
}
1. Install the appropriate JDBC libraries according to ur Operating System/System configuration
2. Need to finalize the URL to connect to the Database
3. need to include the Directory of the JDBC library to the "CLASSPATH" environment varaiable.
4. Run the Program.
We can get appropriate JDBC driver from different Vendors.. following link will give the Details about the which Driver to Choose and all
http://developers.sun.com/product/jdbc/drivers
Download the appropriate Driver and install.
The main thing in running a JDBC program is deciding the Conncetion URL.
The URL string looks like this:
"jdbc:informix-sqli://hostname:port_num/database_name:informixserver=server;user=user;password=pwd"
where jdbc is the main protocol and informix-sqli is the sub protocol
and all other fields are self explanatory
example link :
jdbc:informix-sqli://scsibox:1526/my_data:informixserver=ol_scsibox;user=informix;password=Informix
use the Driver name as "com.informix.jdbc.IfxDriver"
so remaining all we can find from SUN help... i.e.. different classess and all..
one sample program:
import java.sql.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import sqlj.runtime.ref.DefaultContext;
public class ConnectionManager
{
String DRIVER = null ; //JDBC Driver class
String DBURL = null ; //Database URL
String PWD = null, UID = null ; //Password for database account
DefaultContext ctx;
Statement stmt;
public Connection conn;
public Driver d;
String Query = null;
ResultSet rs = null;
int rc = -1;
//This block has to be changed and ConnectionManager.java recompiled
//Assign Default values for Driver loading...
public ConnectionManager(){
DRIVER = "com.informix.jdbc.IfxDriver";
DBURL = "jdbc:informix-sqli://10.128.96.66:5030/omcdb:informixserver=omc_sys1;"+
"username=informix;password=informix";
UID = "informix";
PWD = "informix";
//Establish connection
newConnection();
}
public ConnectionManager(String sDriver, String sDBUrl,String sUID,String sPWD){
DRIVER = sDriver;
DBURL = sDBUrl;
UID = sUID;
PWD = sPWD;
//Establish connection
newConnection();
}
public void newConnection()
{
try
{
d = (Driver)(Class.forName( DRIVER ).newInstance());
DriverManager.registerDriver(d);
System.out.println("Informix Driver Successfully Created....");
}
catch (Exception e)
{
System.err.println( "Could not load driver: " + DRIVER ) ;
System.err.println(e) ;
System.exit(1) ;
}
try
{
conn = DriverManager.getConnection (DBURL, UID, PWD);
//conn.setAutoCommit(false); // Turn AutoCommit off
System.out.println("Created Connection successfully to the Database");
}
catch (SQLException exception)
{
System.out.println("Error: could not get a connection");
System.err.println(exception) ;
exception.printStackTrace();
System.exit(1);
}
}
public void setSQLQuery(String query){
Query = query;
}
//This Method is only to execute statments which dont return Result set...
public int executeQuery(){
rc = -1;
try{
stmt = conn.createStatement();
rc = stmt.executeUpdate(Query);
System.out.println("Transaction successful .. Updated Rows : " + rc);
}catch(SQLException e){
System.out.println("FAILED: execution failed - statement: " + Query);
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
try{
stmt.close();
}catch(SQLException e){
}
return rc;
}
//This shoulb be used with select like queries... which result Resultset...
public ResultSet fetchResultset(){
rs = null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(Query);
System.out.println("Fetched Result Set Successfully");
}catch(SQLException e){
System.out.println("FAILED: execution failed - statement: " + Query);
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
try{
stmt.close();
}catch(SQLException e){
}
return rs;
}
public void closeResultset(){
try{
rs.close();
rs = null;
}catch(SQLException e){
}
}
public DefaultContext initContext(){
ctx = DefaultContext.getDefaultContext();
if (ctx == null) {
try {
newConnection();
ctx = new DefaultContext(conn);
}
catch (SQLException e) {
System.out.println("Error: could not get a default context");
System.err.println(e) ;
System.exit(1);
}
DefaultContext.setDefaultContext(ctx);
}
return ctx;
}
}
executing command in Java
try {
// Execute a command without arguments
String command = "ls";
Process child = Runtime.getRuntime().exec(command);
// Execute a command with an argument
command = "ls /tmp";
child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}
If an argument contain spaces, it is necessary to use the overload that requires the command and its arguments to be supplied in an array: try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};
commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
}
Subscribe to:
Posts (Atom)