JAVA 使用哈希表操作数据库的例子 Using Hashtables to Store & Extract results from a Database.

类别:Java 点击:0 评论:0 推荐:

 

 
使用哈希表操作数据库的例子 // * This code is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
// ********************************************************************
//
// Using Hashtables to Store & Extract results from a Database.
//
// These functions are an example on how to get the data out of a
// resultset from a database and store the values in a Hashtable.
// several of the function are then an example on how to get the data
// out of the hashtables. Why would you want to do all this work?
// Maintaining a database connection over the web is expensive. By
// dumping the data into a hashtable you can minimize the amount of
// time you stay connected to your database. Also by storing the data
// in a hashtable offers flexible way to pass your data from
// object to object.
//
// This is a set of five functions
//
// Function makeHashTable :
// Takes a database ResultSet and places the data into a
// Hashtable array for later use.
//
// Function cleanHashTable :
// Takes a Hashtable array and removes the unused portion
// of a hashtable array. For example: You use makeHashTable
// and since it allocates the hashtable array in chunks of 20,
// its possible that it creates a hashtable of size 40, but
// only the first 22 indexes are used. So makeHashTable calls
// the cleanHashTable function which resizes the Hashtable
// array to only 22 indexes.
//
//Function columnOrder:
// Since a Hashtable does not guarantee to maintain the order
// of the elements put into it. This function produces a
// hashtable to store the column order of the ResultSet
//
//Function hastToTabFile
// An example on how to take a hashtable produced by the
// makeHashTable function and turn it into a tab delimited
// output string (used to download a dataresult as a flatfile)
// This function uses a the results from the columnOrder
// function to navigate the hashtable. If this function can`t
// find this index hashtable, it then passes the hashtable
// to the hashToTab Function to step through the hashtable using
// enumeration methods.
//
//Function hashToTab
// If no index hasharray was found then this function uses
// Enumeration to step through the Hashtable and return a
// result
//
//////////////////////////////////////////////////////////////////////////
//
// Please note the following.
// -I suspect using a Vector would give much faster results .
// -If you are using Java 1.2 You should consider using an ArrayList,
// HashSet or TreeSet rather than a Hashtable or a Vector.
// -Use a Hashtable or Vector when you want java 1.1.x compatibility
//
//////////////////////////////////////////////////////////////////////////

public Hashtable[] makeHashTable(ResultSet ars_data)
{
int li_columns = 0;
int li_rowcount = 0;

Hashtable[] lht_results = new Hashtable[20];


try
{ // 1)get the column count and store our column order information
// in our first index of our Hashtable array
ResultSetMetaData lmeta_data = ars_data.getMetaData();

li_columns = lmeta_data.getColumnCount();

if (li_columns > 0)
{ lht_results[li_rowcount] = columnOrder(lmeta_data,li_columns);
li_rowcount++;
}


// 2)loop through the result set and add the data 1 row at a time to
// the hashtable array
while (ars_data.next())
{
// 3) If we are at the last index of our hashtable then expand it
// by another 20 indexes
if (li_rowcount == lht_results.length)
{
Hashtable[] lht_temp = new Hashtable[lht_results.length + 20];
for (int li_loop = 0; li_loop < lht_results.length ; li_loop++)
{
lht_temp[li_loop] = lht_results[li_loop];
}
lht_results = lht_temp;
}

// 4) loop through our column information and add it to our hash array
Hashtable lht_row = new Hashtable(1);
for ( int i = 1; i <= li_columns; i++)
{
Object luo_value = null;
try
{
luo_value = ars_data.getObject(i);
}
catch(Exception e){}
if (luo_value ==null) luo_value = new String("");
lht_row.put(lmeta_data.getColumnLabel(i),luo_value);
}

lht_results[li_rowcount] = lht_row;
li_rowcount++;


}
}
catch(SQLException e)
{
}


if (lht_results[0] == null)
{
return null;
}


return cleanHashTable(lht_results);
}



private Hashtable[] cleanHashTable(Hashtable[] aht_data)
{
Hashtable[] lht_temp = null;
int li_total_rows = aht_data.length;

// 1) loop thru and determine where the first null row appears
for (int i=0; i<aht_data.length; i++)
{
if (aht_data == null)
{
li_total_rows = i;
break;
}
}

// 2) rebuild a new hashtable array of the right size
// and reload it with your data
if (li_total_rows < aht_data.length)
{ lht_temp = new Hashtable[li_total_rows];

for (int i=0; i<li_total_rows; i++)
{
lht_temp[i] = aht_data[i];
}

aht_data = lht_temp;
lht_temp = null;
}

return aht_data;
}


private Hashtable columnOrder(ResultSetMetaData ameta_data, int ai_columns)
{
// 1) Size the Hashtable to be slighly larger than column count
// and load factor to 1 so the hash table wont have to resize itself.
Hashtable lht_row = new Hashtable((ai_columns + 3),1);

try
{ // 2) Store how many columns we have.
lht_row.put("Column_Count",String.valueOf(ai_columns));

// 3) Loop thru and store each column label and use its position
// number as its key
for ( int i = 1; i <= ai_columns; i++)
{
lht_row.put(String.valueOf(i),ameta_data.getColumnLabel(i));
}
}
catch (SQLException e)
{ // 4 Return a null result if an error happens
lht_row = null;
}

return lht_row;
}


public String hastToTabFile(Hashtable[] ahash_data, boolean ab_header)
{ //*****************************************************************
// ahash_data: array of hashtables to convert to tabfile
// ab_header : True if you want the tab file to include the headers
//*****************************************************************
String ls_tabfile = "";

if (ahash_data == null)
{ // 1) if no data then return empty file
ls_tabfile = "";
}
else
{
// 2) first get column headers
int li_column_count = 0;
String ls_column_count = ahash_data[0].get("Column_Count").toString();
try
{
li_column_count = Integer.parseInt(ls_column_count);
}
catch(NumberFormatException e)
{
// 3) since this hashtable doesnt have the the column data stashed
// treat it as a normal hashtable array
return hashToTab(ahash_data,ab_header);
}


// 4) Gather up each columns label/key name also build up the header column
String[] ls_indexes = new String[li_column_count];

for(int icol = 0; icol < li_column_count; icol++)
{
ls_indexes[icol] = ahash_data[0].get(String.valueOf(icol+1)).toString();
if(ab_header) ls_tabfile = ls_tabfile + ls_indexes[icol] + " ";
}


// 5) Include the headers in the file if user requested them
if(ab_header) ls_tabfile = ls_tabfile + " ";


// 6) loop through and gather tha data to display
for (int irow=1; irow < ahash_data.length; irow++)
{ if (ahash_data[irow] != null)
{
for(int icol = 0; icol < li_column_count; icol++)
{
ls_tabfile = ls_tabfile + ahash_data[irow].get(ls_indexes[icol]).toString() + " ";
}
ls_tabfile = ls_tabfile + " ";
}
}
}

return ls_tabfile;
}


private String hashToTab(Hashtable[] ahash_data, boolean ab_header)
{//*****************************************************************
// ahash_data: array of hashtables to convert to tabfile
// ab_header : True if you want the tab file to include the headers
//*****************************************************************
String ls_tabfile = "";

if (ahash_data == null)
{ // 1) if no data return empty file
ls_tabfile = "";
}
else
{
// 2) IF requested print out the header files
if (ab_header)
{
for(Enumeration lenum_header = ahash_data[0].keys(); lenum_header.hasMoreElements();)
{
String ls_col = lenum_header.nextElement().toString() + " ";
ls_tabfile = ls_tabfile + ls_col;
}
ls_tabfile = ls_tabfile + " ";
}

// 3) Loop through the rows and gather tha data to display
for (int i=0; i < ahash_data.length; i++)
{ Hashtable lhash_row = ahash_data[i];
if (lhash_row != null)
{ // 4) Loop thru each column and prints the columns data
for(Enumeration l_enum = lhash_row.keys(); l_enum.hasMoreElements();)
{
String ls_col = l_enum.nextElement().toString() ;
ls_tabfile = ls_tabfile + lhash_row.get(ls_col).toString() + " ";
}
ls_tabfile = ls_tabfile + " ";
}
}
}

return ls_tabfile;
}

(作者:  来源:jsp爱好者)

本文地址:http://com.8s8s.com/it/it18785.htm