电子通讯薄(MVC) :此示例基于MVC模式,包含四个界面:登入、添加数据、查询数据和显示所有数据,通过这个示例将会对Struts构架有进一步的了解
源代码在线查看: addressbookbean.java
package addressbook.model;
import java.sql.*;
import java.util.*;
import addressbook.Constants;
public class AddressBookBean
{
private Connection con;
public AddressBookBean()
{
try{
this.con = DbUtil.getConnection();
}catch(Exception e){
System.out.println("e"+e.getMessage());
}
}
public void insert(AddressBook addressBook)throws Exception
{
PreparedStatement pStmt=null;
pStmt=con.prepareStatement("insert into book(name,phone,address) values(?,?,?)");
pStmt.setString(1,addressBook.getName());
pStmt.setString(2,addressBook.getPhone());
pStmt.setString(3,addressBook.getAddress());
try
{
pStmt.executeUpdate();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
pStmt.close();
con.close();
}
catch(Exception e)
{e.printStackTrace();}
}
}
public Collection search(String strSql)throws Exception{
Statement Stmt=con.createStatement();
Collection ret=new ArrayList();
ResultSet rs=Stmt.executeQuery(strSql);
try
{
while(rs.next())
{
AddressBook temp=new AddressBook();
temp.setName(rs.getString("name"));
temp.setPhone(rs.getString("phone"));
temp.setAddress(rs.getString("address"));
ret.add(temp);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
rs.close();
Stmt.close();
con.close();
}
catch(Exception e)
{e.printStackTrace();}
}
return ret;
}
}