思路:
连接数据库的类
package com.dhj.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 提供了一组获得或关闭数据库对象的方法
*
*/
public class DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password; static {// 静态块执行一次,加载 驱动一次
try {
InputStream is = DBAccess.class
.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获得数据连接对象
*
* @return
*/
public static Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(conn);
}
public static boolean isOracle() {
return "oracle.jdbc.driver.OracleDriver".equals(driver);
}
public static boolean isSQLServer() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
}
public static boolean isMysql() {
return "com.mysql.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:ora9
#user=test
#pwd=test
#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1423;DatabaseName=test
#user=sa
#pwd=sa
#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888
#mysql5
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/wd?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123
package com.dhj.util;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 20;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
package com.dhj.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
package com.dhj.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码处理
*
*/
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
package com.dhj.entity;
public class Book {
private int bid;
private String bname;
private float price;
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
super();
}
}
package com.dhj.dao;
import com.dhj.entity.Book;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.dhj.util.DBAccess;
import com.dhj.util.PageBean;
import com.dhj.util.StringUtils;
public class BookDao extends DemoDao{
/**
* @param book 封装着jsp传递过来的查询参数
* @param pageBean 决定dao层的list调用时是否分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
String sql = "select * from t_mvc_book where true ";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql += " and bname like '%"+bname+"%'";
}
return super.executeQuery(sql, Book.class, pageBean);
}
//测试方法是否成功
public static void main(String[] args) {
BookDao bookDao = new BookDao();
Book book = new Book();
book.setBname("圣墟");//设置模糊查询条件 bname
PageBean pageBean = new PageBean();
pageBean.setPage(1);//设置页数 每页数量默认20条
try {
List list = bookDao.list(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
package com.dhj.dao;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.dhj.entity.Book;
import com.dhj.util.DBAccess;
import com.dhj.util.PageBean;
import com.dhj.util.StringUtils;
/**
* 通用的查询(带条件查询)
* @author 10237
*
*/
public class BeanDao {
/**
* @param sql 由于不同的表查询语句不一样,所以靠子类写好来传递
* @param cls 需要返回不同的对象集合 查询的对象
* @param bean 可能要分页
* @return
* @throws Exception
*/
public List sqlBean (String sql,Class cls,PageBean bean) throws Exception{
List list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
T t = null;
while (rs.next()) {
/**
* 1. 实例化一个你要查询的对象 (比如book)
* 2. 通过对象的属性名去游标中取出属性值(通过反射来完成)
* 2.1 获取到类对象中的属性
* 2.2 给属性赋值
* 3. 已经赋值好的实例对象放入到list集合当中
*/
t = (T) cls.newInstance();//反射获取对象开始
Field [] fields = cls.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);//打开权限
// 对象 对象的属性名
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
return list;
}
}
package com.dhj.dao;
import java.util.List;
import com.dhj.entity.Book;
import com.dhj.util.PageBean;
import com.dhj.util.StringUtils;
/**
* 测试通用查询(带条件)
* @author 10237
*
*/
public class BookDao2 extends BeanDao{
public List list(Book book,PageBean bean) throws Exception{
String sql = "select * from t_mvc_book where true";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql += " and bname like '%"+bname+"%'";
}
return super.sqlBean(sql, Book.class, bean);
}
//测试
public static void main(String[] args) throws Exception {
BookDao2 bookDao2 = new BookDao2();
Book book = new Book();
book.setBname("斗破");
List list = bookDao2.list(book, null);
for (Book book2 : list) {
System.out.println(book2);
}
}
}
package com.dhj.dao;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.dhj.util.DBAccess;
import com.dhj.util.PageBean;
/**
* 通用分页查询(带条件查询)
* @author 10237
*
*/
public class BeanDao2 {
/**
*
* @param sql 由于不同的表查询语句不一样,所以靠子类写好来传递
* @param cls 需要返回不同的对象集合 查询的对象
* @param bean 可能要分页
* @return
* @throws Exception
*/
public List sqlBean (String sql,Class cls,PageBean bean) throws Exception{
List list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
//决定是否分页:
if(bean != null && bean.isPagination()) {//判读条件
//分页
/**
* 1.分页是与分页助手类pagebean中的total有关,需要查询数据库得到total赋值给bean
* 2.查询出符合条件的某一页的数据
*/
String countsql = getCountsql(sql);
ps = con.prepareStatement(countsql);
rs = ps.executeQuery();
/**
* -- 符合条件的记录数
select count(1) from (select * from t_mvc_book where bname like '%斗破%') t;
*/
if(rs.next()){
bean.setTotal(rs.getObject(1).toString());//查询多少条数据
}
/**
* --分页的查询语句
select * from t_mvc_book where bname like '%斗破%' limit 起始下标(第几页),变量(每页显示几条)
*/
String pagesql = getPagesql(sql, bean);
ps = con.prepareStatement(pagesql);
rs = ps.executeQuery();
}else {
//不分页
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
}
T t = null;
while (rs.next()) {
/**
* 1. 实例化一个你要查询的对象 (比如book)
* 2. 通过对象的属性名去游标中取出属性值(通过反射来完成)
* 2.1 获取到类对象中的属性
* 2.2 给属性赋值
* 3. 已经赋值好的实例对象放入到list集合当中
*/
t = (T) cls.newInstance();//反射获取对象开始
Field [] fields = cls.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);//打开权限
// 对象 对象的属性名
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
return list;
}
/**
*
* @param sql
* @param bean 获取查询的起始下标和变量
* @return
*/
private String getPagesql(String sql , PageBean bean) {
// TODO 分页查询语句
return sql + " limit " +bean.getStartIndex()+","+bean.getRows();
}
private String getCountsql(String sql) {
// TODO 用来查询对应条件有多少条数据
return "select count(1) from ("+sql+") t";
}
}
package com.dhj.dao;
import java.util.List;
import com.dhj.entity.Book;
import com.dhj.util.PageBean;
import com.dhj.util.StringUtils;
/**
* 测试通用分页查询(带条件)
* @author 10237
*
*/
public class BookDao3 extends BeanDao2{
public List list(Book book,PageBean bean) throws Exception{
String sql = "select * from t_mvc_book where true";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql += " and bname like '%"+bname+"%'";
}
return super.sqlBean(sql, Book.class, bean);//父类的查询方法
}
//测试
public static void main(String[] args) throws Exception {
BookDao3 bookDao3 = new BookDao3();
Book book = new Book();
book.setBname("斗破");
PageBean bean = new PageBean();
//bean.setPagination(false);//控制是否分页,默认为true 分页 false 不分页
//bean.setPage(2);//设置查询页数 默认查询第一页
bean.setRows(2);//设置每页显示条数 默认3条
List list = bookDao3.list(book, bean);
for (Book book3 : list) {
System.out.println(book3);
}
System.out.println(bean);
}
}