Friday, August 27, 2010

String split in java

/*

Java String split example.

This Java String compare example describes how Java String is splited into multiple Java String objects.

*/

public class JavaStringSplitExample{

public static void main(String args[]){

/*

Java String class defines following methods to split Java String object.

String[] split( String regularExpression )

Splits the string according to given regular expression.

String[] split( String reularExpression, int limit )

Splits the string according to given regular expression. The number of resultant substrings by splitting the string is controlled by limit argument.

*/

/* String to be splitted. */

String str = "one-two-three";

String[] temp;

/* delimeter */

String delimeter = "-";

/* given string will be splitted by the argument delimeter provided. */

temp = str.split(delimeter);

/* print splitted substrings */

for(int i =0; i < temp.length ; i++)

System.out.println(temp[i]);

/*

IMPORTANT : Some special characters needs to be escaped while providing them as delimeters like "." and "|".

*/

System.out.println("");

str = "one.two.three";

delimeter = "\\.";

temp = str.split(delimeter);

for(int i =0; i < temp.length ; i++)

System.out.println(temp[i]);

/*

Using second argument in the String.split() method, we can control the maximum number of substrings generated by splitting a string.

*/

System.out.println("");

temp = str.split(delimeter,2);

for(int i =0; i < temp.length ; i++)

System.out.println(temp[i]);

}

}

/*

OUTPUT of the above given Java String split Example would be :

one

two

three

one

two

three

one

two.three

*/

Friday, August 13, 2010

How to get the size of ResultSet (total number of rows/columns)?

To Get ColumnCount:

ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();

To Get RowCount:

1. Using Query


// Get a record count with the SQL Statement
Statement stmt = connection.createStatement();
String strQry = "SELECT COUNT(*) AS rowcount FROM Person";
ResultSet rs = stmt.executeQuery(strQry);
rs.next();

// Get the rowcount column value.
int ResultCount = rs.getInt(rowcount) ;

rs.close() ;


2. Using Scrollable ResultSet:


String strQuery = "SELECT * FROM Person";

// Create a scrollable ResultSet.
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(strQuery);

// Point to the last row in resultset.
rs.last();

// Get the row position which is also the number of rows in the ResultSet.
int rowcount = rs.getRow();

System.out.println("Total rows for the query: "+rowcount);


// Reposition at the beginning of the ResultSet
rs.beforeFirst();