上传者: yazhengq
|
上传时间: 2021-11-03 14:34:09
|
文件大小: 376KB
|
文件类型: -
用MVC模式的实现对数据库的增删改查
部分代码:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import common.DBConnection;
import bean.Contact;
public class ContactDAO {
public List getAllContact() throws Exception{
Connection conn=DBConnection.getConntion();
PreparedStatement ps=conn.prepareStatement("select * from Contact");
ResultSet rs=ps.executeQuery();
List list = new ArrayList();
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String phone = rs.getString("phone");
String address = rs.getString("address");
Contact c = new Contact();
c.setId(id);
c.setName(name);
c.setPhone(phone);
c.setAddress(address);
list.add(c);
}
rs.close();
ps.close();
conn.close();
return list;
}
public void addContact(String name,String phone,String address) throws Exception{
String sql = "insert into contact(id,name,phone,address) values(seq_contact.nextval,?,?,?)";
Connection con = DBConnection.getConntion();
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, phone);
pstmt.setString(3, address);
pstmt.executeUpdate();
}
public void delContact(int id) throws Exception{
String sql = "delete from contact where id=?";
Connection con = DBConnection.getConntion();
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
}
public Contact getContactById(int id) throws Exception{
String sql = "select * from Contact where id=?";
Connection con = DBConnection.getConntion();
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
Contact c = null;
while(rs.next()){
// int id = rs.getInt("id");
String name=rs.getString("name");
String p