标签:
既然是分层开发,首先我们需要知道的是分为那几个层,并且是干什么的?
1.实体层(entity) 对应数据库中的一张表,有了它可以降低耦合性,同时也是数据的载体.
2.数据访问对象(data access object)主要包含两个java源文件,一个是BaseBao,还有一个是所需要查询表的接口
package cn.news.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.Test; /** * 数据访问工具类 * @version 1.1 * @author happy * */ public class BaseDao { private static final String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String url="jdbc:sqlserver://localhost:1433;DataBaseName=s2223"; private static final String username="sa"; private static final String pwd="6375196"; Connection con=null; PreparedStatement ps=null; ResultSet rs=null; //01.写一个用户获取到一个连接对象的方法,方法的返回值是Connection类型 /** * 01.写一个用户获取到一个连接对象的方法,方法的返回值是Connection类型 * @return 连接对象 * @throws Exception */ public Connection getConnection() throws Exception{ Class.forName(driver); //什么条件下,构建connection对象 if (con==null||con.isClosed()) { con=DriverManager.getConnection(url, username, pwd); } //同志们碰到一个 return con; } //单元测试 //java junit @Test public void testQuery() throws Exception{ ResultSet rs = executeQuery("select * from student"); if(rs!=null){ while (rs.next()) { String name = rs.getString("sname"); System.out.println(name); } } } //测试添加 @Test public void testUpdate() throws Exception{ int count= executeUpdate("update student set sname=‘大强‘ where sname=‘黄强‘"); System.out.println(count); } //执行查询操作 目的:返回一个读取器 /** * 执行查询操作 目的:返回一个读取器 * @param sql sql语句 * @param objs 参数列表 * @return 读取器对象 * @throws Exception */ public ResultSet executeQuery(String sql,Object... objs) throws Exception{ con=getConnection(); ps = con.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { ps.setObject(i+1, objs[i]); } rs= ps.executeQuery(); return rs; } //执行增删该操作 /** * 执行增删该操作 * @param sql sql语句 * @param objs 参数列表 * @return 受影响行数 * @throws Exception */ public int executeUpdate(String sql,Object... objs) throws Exception{ con=getConnection(); ps = con.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { ps.setObject(i+1, objs[i]); } int count = ps.executeUpdate(); return count; } //2.回收连接资源 /** * 回收连接资源 * @throws Exception */ public void closeAll() throws Exception{ if(rs!=null){ rs.close(); } if (ps!=null) { ps.close(); } if(con!=null){ con.close(); } } }
3.数据访问层的
标签:
原文地址:http://www.cnblogs.com/myhome-1/p/5561208.html