数据库的相关操作:如连接、查询、添加、删除、修改、分页显示
package study.database;
/**
* <p>Title: JSP模式学习</p>
* <p>Description: 数据库的相关操作:如连接、查询、添加、删除、修改</p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author 李艳生
* @version 1.0
*/
import java.sql.*;
import java.io.*;
import java.util.*;
public class Operation {
//数据库驱动程序
private String strDriver = "";
//数据库连接字符串
private String strURL = "";
//数据库用户名
private String username = "";
//数据库密码
private String password = "";
private Connection conn = null;
private Statement stmt = null;
ResultSet rs = null;
/** 读到数据库配置信息
*/
private void loadProp(){
InputStream is = getClass().getResourceAsStream("/setup.txt");
Properties props = new Properties();
try{
props.load(is);
}catch(Exception e){
System.err.println("不能读取配置文件. 请确保setup.txt在classes指定的路径中");
}
Enumeration propNames = props.propertyNames();
while (propNames.hasMoreElements()) {
String name = (String) propNames.nextElement();
if (name.endsWith(".driver")) {
String poolName = name.substring(0, name.lastIndexOf("."));
strDriver = props.getProperty(poolName + ".driver");
strURL = props.getProperty(poolName + ".url");
username = props.getProperty(poolName + ".user");
password = props.getProperty(poolName + ".password");
}
}
}
/** 在创建Operation对象时连接数据库
*/
public Operation() {
//读到数据库配置信息
loadProp();
try{
Class.forName(strDriver);
}catch(java.lang.ClassNotFoundException e) {
System.err.println("数据库连接错误:" + e.getMessage());
}
try{
conn=DriverManager.getConnection(strURL,username,password);
}catch(SQLException ex) {
System.err.println("数据库连接错误:" + ex.getMessage());
}
}
/** 数据库查询
* sql:SQL查询语句
*/
public ResultSet query(String sql) {
try{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
}catch(SQLException ex) {
System.err.println("数据库查询错误:" + ex.getMessage());
}
return rs;
}
/** 数据库添加、修改、删除
* sql:SQL语句
*/
public void update(String sql) {
try{
stmt=conn.createStatement();
stmt.executeUpdate(sql);
}catch(SQLException ex) {
System.err.println("数据库更新错误:"+ex.getMessage());
}
}
/** 得到查询结果的总记录数
* rs:查询结果集
*/
public int totalRecord(ResultSet rs) throws Exception{
int total=0;
//指针移到最后一条记录上
rs.last();
total = rs.getRow();
rs.first();
return total;
}
/** 分页显示
* currPage: 当前页数
* pageSize: 页大小
* pageCount: 总页数
* filename: 使用分页的文件名(文件名后面要加?,多个参数以&分开,有参数的最后以&结束)
* http://www.knowsky.com/ 返回字符串: <a href="filename?page=当前页数">
*/
public String showPages(int currPage, int pageSize, int pageCount, String filename){
String addr;
addr = "<table width=100% border=0 align=center cellpadding=0 cellspacing=0><form method=Post name=pageform><tr><td><div align=right>当前第<strong><font color=red>" + currPage + "</font></strong>页 " +
"共<strong><font color=red>" + pageCount + "</font></strong>页每页<strong><font color=red>" + pageSize + "</font></strong>条 ";