package com.ejb;
import java.sql.Connection;
import java.util.ArrayList;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* It's just a fun,i only resolve a question for a net fiend.
* I am a chinese, i learn
ejb 2 years,if my anwers you can't resolve
* your question communicate with me.
* @author xunn(
[email protected])
* 2003-12-16 9:41
*/
public class Finder{
public static Connection conn ;
private static StringBuffer queryNames =
new StringBuffer("select * from ");
private static String tableName = "mytable";
/**
*construstor now create connection
*/
public Finder(){
if(conn == null){
//create a Connection ,DriverFactory is
//my Connection factory can crete an database connection.
conn = DriverFactory.getConnection();
}
}
/**
* construstor now create connection and
* give the class member tableName a real table name;
*/
public Finder(String tableName){
if(conn == null){
//create a Connection ,DriverFactory is my
// Connection factory can crete an database connection.
conn = DriverFactory.getConnection();
}
this.tableName = tableName;
}
/**
* use a StringBuffer to make sql,current return is ArrayList
* you can use return an Object
* has more set or get method.I use ArrayList
* ,It's a simple resolve method.
* findByPersonNames(String [] names)
* If names array is null, I should get all Persons.
* If names array has one name,
* then I sould get one Person
* If names array has two names,
* then I sould get two Persons, and so on.
* question resolve, ok?
*/
public ArrayList findByPersonNames(String[] names){
ArrayList ret = new ArrayList();
Statement stmt = null;
ResultSet rs = null;
queryNames.append(tableName);
if(names != null){
queryNames.append(" where ");
for(int i = 0;i<names.length;i++){
if(i == 0)
queryNames.append(" name=").append(names[i]);
else
queryNames.append(" or name=").append(names[i]);
}
}
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(queryNames.toString());
while(rs.next()){
//you can use getString or other method to
//choose which you will be used
ret.add(rs.getObject(1));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}finally{
try{
if(rs != null) rs.close();
if(stmt != null) stmt.close();
}catch(SQLException ex){
ex.printStackTrace();
}
}
return ret;
}
/**
*I have the following three find methods:
*findByName(String name)
*findByAge(int age)
*findByNameAndAge(String name, int age)
* you can use same way to resolve your question.
* good luck to you .
*/
}