日期:2014-05-20  浏览次数:20712 次

Java DB操作类的设计代码
如题。怎么设计最合理?

------解决方案--------------------
Java code

public class DB{
 public static return_type method(){
  //statement...
 }
}
interfere DBoperation{
abstract public return_type method();
abstract public return_type method(/*参数*/);

}
DB implement DBoperation{
//statement...
}

------解决方案--------------------
Java数据库操作类
package bean;
import java.sql.*;
public class Admin 
{
String DBDriver="sun.jdbc.odbc.JdbcOdbcDriver";
private Connection conn=null;
private Statement stmt=null;
ResultSet rs=null;
//修改DBUrl值可连接不同类型的数据库-ODBC/JDBC等等
public String DBUrl="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
public Admin(){
try{//注册
Class.forName(DBDriver);
}
  
catch(java.lang.ClassNotFoundException e)
{
System.err.println("出错啦!!数据库注册出毛病了!!!"+e.getMessage());
}
}
//输入为本地数据库(*.*.mdb相对路径)
public String getDataPath(String s)//非mdb数据库这个方法裁剪
{
DBUrl =new String(DBUrl + s);
return DBUrl;
}
public ResultSet executeQuery(String sql)
{ rs=null;
try{//连接数据库查询
conn=DriverManager.getConnection(DBUrl);
//有密码的用conn=DriverManager.getConnection(DBUrl, ''用户名", "密码");
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
}
catch(SQLException ex)
{
System.err.println("暂时无法连接数据库!!"+ex.getMessage());
}
return rs;

public ResultSet selectQuery()
{
String sql = "select * from T_MIR"; 
rs=null;
try{//连接数据库查询
conn=DriverManager.getConnection(DBUrl);
//有密码的用conn=DriverManager.getConnection(DBUrl, ''用户名", "密码");
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
}
catch(SQLException ex)
{
System.err.println("数据库查询出毛病了!!"+ex.getMessage());
}
return rs;

}
  
public void executeUpdate(String sql)
{
stmt=null;
rs=null;
try{
conn=DriverManager.getConnection(DBUrl);
//有密码的用conn=DriverManager.getConnection(DBUrl, ''用户名", "密码");
stmt=conn.createStatement();
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException ex)
{
System.err.println("暂时无法连接数据库!!"+ex.getMessage()); 
}
}
public void closeStmt()
{
try{
stmt.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public void closeConn()
{
try{
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}