我是这样做的,写了一个类,然后封装了所有的取得必要信息的方法,比如
Class UserInfo
  public boolean OpenUser(String UserName)
  public String GetUserName()
  public int GetUserAge()
  public Date GetUserBirthday()这样,在JSP端就不必考虑数据库细节,直接使用,比如
  UserInfo ui = new UserInfo();
  if (ui.OpenUser("Adai")){
     out.println("UserName:"+ui.GetUserName());
     ...
   }else{
     out.println("No such user");
   }

解决方案 »

  1.   

    感谢adailee(不谈恋爱的铅笔)!!!不过有几点我希望您能给予指点,一是在bean里如何把字段值赋给一个变量?
    还有就是比如说我要取得这个记录有50个字段,那要写50个GET...()函数了?
    顺便请给出随便您的一个GET...()函数,谢谢啦!!!我是初学者,不好意思,呵呵
      

  2.   

    感谢adailee(不谈恋爱的铅笔)!!!不过,有几点请您指点,一是我想知道如何在bean里把字段值赋给一个变量的。如果可以希望能看到您写的这个bean,谢谢!!!还有就是假如这条记录有50个字段,那就要写50个GET...()函数了?不好意思,我是个初学者,呵呵
      

  3.   

    使用javax.sql.DatabaseMetaData/可以做到.你要通过好的设计和编程来做到这个通用的bean
      

  4.   

    寫一個CLASS 作為OUTPUT, OUTPUT CLASS 的变量為PUBLIC, 方便使用
      

  5.   

    public class MyQueryOutput {
       public String field1;
       public String field2; ....}
      

  6.   

    我现在不知道的地方是在bean中如何把字段值赋给一个变量,请各位大侠以例示之~谢喽~
      

  7.   

    input class:public  class  MyQueryInput  { 
          public  String  field1; 
          public  String  field2;  .... }
    output class:
    public  class  MyQueryOutput  { 
          public  String  field1; 
          public  String  field2;  .... }
    your query bean:
    ...
    ...
    public MyQueryOutput myQueryMethod(MyQueryInput input) {
    ....
    }
    In your jsp:
    MyQueryInput prepareInput = new MyQueryInput();
    prepareInput.XXX = XXX;
    ....MyQueryOutput myOutput = your_bean.myQueryMethod(prepareInput);
    ....
      

  8.   

    非常感谢cosmo(MoMo)!!!谢谢你写了这么多代码,不过我现在首先要知道如何在bean中把提起出来的数据集(rs)中每个字段赋给每一个变量上,如果您有msn请加我,可以聊聊,我的msn:[email protected]
      

  9.   

    use output.field1 = rs.getString("YOUR_FIELD_NAME");  //if it is a stringuse getDate, getInt, etc to get other type
      

  10.   

    这不是和jsp页面中一样吗?在bean中确实是这样?我以前这样试过,没通,以为是我用的方法根本错误,现在看来不是啦!太感谢啦!
      

  11.   

    我首先自己写了一个database类,来处理数据的读取、写入。
    不然,你每次读取的时候都要try catch。
    其他类从database继承。
    package com.we.system.db;/**
     * <p>Title: Museum Relic Magament</p>
     * <p>Description: The first software with Jaca</p>
     * <p>Copyright: Copyright (c) 2002</p>
     * <p>Company: WestEngine corporation</p>
     * @author Adai lee
     * @version 0.0.0.1
     */import java.sql.*;
    import java.sql.ResultSet;
    import java.util.Date;
    import java.text.SimpleDateFormat;public class database {  /**
       * Create the database Class
       */
      public database() {
      }  /**
       * Get a DataSet.
       * @param connection Connection
       * @param sql SQL
       * @return The ResultSet
       */
      public ResultSet QueryData(Connection connection, String sql) {
        ResultSet resultset = null;
        Statement statement = null;
        int dType = java.sql.ResultSet.TYPE_FORWARD_ONLY;
        int dConcur = java.sql.ResultSet.CONCUR_UPDATABLE;
        try{
          statement = connection.createStatement(dType, dConcur);
    //      String str = new String(sql.getBytes("GB2312"),"ISO-8859-1");
          resultset = statement.executeQuery(sql);
          resultset.first();
          System.out.println("SQL: "+sql);
        }catch(Exception e){
          System.out.println(e.getClass() +  "QueryDate" + e.toString());
        }
        return resultset;
      }  /**
       * ExecuteSQL
       * @param connection The Connection
       * @param sql The SQL
       * @return Wheather the SQL execute.
       */
      public boolean ExecuteSQL(Connection connection, String sql) {
        boolean Result = false;
        Statement statement = null;
        try{
          statement = connection.createStatement();
          String str = new String(sql.getBytes("ISO-8859-1"),"GB2312");
          Result = statement.execute(str);
        }catch(Exception e){
          System.out.println(this.getClass()+"ExecuteSQL()"+e.toString());
        }
        return Result;
      }  public boolean UpdateRow(ResultSet resultset) {
        boolean Result = false;
        try{
          resultset.updateRow();
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+"UpdateRow()"+e.toString());
        }
        return Result;
      }  public boolean CancleUpdateRow(ResultSet resultset) {
        boolean Result = false;
        try{
          resultset.cancelRowUpdates();
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+":CancleUpdateRow():"+e.toString());
        }
        return Result;
      }  public boolean DeleteRow(ResultSet resultset) {
        boolean Result = false;
        try{
          System.out.println("Delete..."+resultset.getString(1));
          resultset.deleteRow();
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+":DeleteRow():"+e.toString());
        }
        return Result;
      }  public boolean AddRow(ResultSet resultset) {
        boolean Result = false;
        try{
          resultset.moveToInsertRow();
        }catch(Exception e){
          System.out.println(this.getClass()+":AddRow():"+e.toString());
        }
        return Result;
      }  public boolean SaveRow(ResultSet resultset) {
        boolean Result = false;
        try{
          resultset.insertRow();
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+":SaveRow():"+e.toString());
        }
        return Result;
      }  /**
       * Get the field value. convert it to String.
       * @param resultset The Data ResultSet.
       * @param FieldName The Field name.
       * @return The Field Value.
       */
      public String GetString(ResultSet resultset, String FieldName){
        String Result = "";
        try{
    //      Result = resultset.getString(FieldName);
            Result = new String(resultset.getString(FieldName).getBytes("GB2312"),"GB2312");
          if (Result == null) Result = "";
        }catch(Exception e){
          System.out.println(this.getClass()+":GetString():"+e.toString());
        }
        return Result;
      }  public boolean UpdateField(ResultSet resultset, String FieldName, String FieldValue) {
        boolean Result = false;
        try {
    //      String str = new String(FieldValue.getBytes("GB2312"),"ISO-8859-1");
          resultset.updateString(FieldName,FieldValue);
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+":UpdateField():"+e.toString());
        }
        return Result;
      }  public boolean UpdateField(ResultSet resultset, String FieldName, int FieldValue) {
        boolean Result = false;
        try {
          resultset.updateInt(FieldName,FieldValue);
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+":UpdateField():"+e.toString());
        }
        return Result;
      }  /**
       * Update a field values.
       * @param resultset The ResultSet.
       * @param FieldName The Field Name
       * @param FieldValue The Field Value.
       * @return
       */
      public boolean UpdateField(ResultSet resultset, String FieldName, short FieldValue) {
        boolean Result = false;
        try {
          resultset.updateShort(FieldName,FieldValue);
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+"UpdateField()"+e.toString());
        }
        return Result;
      }  public boolean UpdateField(ResultSet resultset, String FieldName, Date FieldValue) {
        boolean Result = false;
        try {
          System.out.println("Update"+FieldValue.toString());
          java.sql.Date dt = (java.sql.Date)FieldValue;
          resultset.updateDate(FieldName, dt);
          Result = true;
        }catch(Exception e){
          System.out.println(this.getClass()+"UpdateField()"+e.toString());
        }
        return Result;
      }  /**
       * Get the field value. convert it to String.
       * @param resultset The Data ResultSet.
       * @param FieldName The Field name.
       * @return The Field Value.
       */
      public int GetInt(ResultSet resultset, String FieldName){
        int Result = -9999;
        try{
          Result = resultset.getInt(FieldName);
        }catch(Exception e){
          System.out.println(this.getClass()+"GetInt()"+e.toString());
        }
        return Result;
      }  /**
       * Get the field value. convert it to String.
       * @param resultset The Data ResultSet.
       * @param FieldName The Field name.
       * @return The Field Value.
       */
      public Date GetDate(ResultSet resultset, String FieldName){
        Date Result = null;
        try{
          Result = resultset.getDate(FieldName);
        }catch(Exception e){
          System.out.println(this.getClass()+"GetDate()"+e.toString());
        }
        return Result;
      }  /**
       * Get the field value. convert it to String.
       * @param resultset The Data ResultSet.
       * @param FieldName The Field name.
       * @return The Field Value.
       */
      public short GetShort(ResultSet resultset, String FieldName){
        short Result = 0;
        try{
          Result = resultset.getShort(FieldName);
        }catch(Exception e){
          System.out.println(this.getClass()+"GetShort()"+e.toString());
        }
        return Result;
      }  public boolean MoveNext(ResultSet rs){
        boolean Result = false;
        try{
          Result = rs.next();
        }catch(Exception e){
          System.out.println(this.getClass()+"MoveNext()"+e.toString());
        }
        return Result;
      }  public int GetRecordCount(ResultSet rs){
        int Result = 0;
        try{
          Result = rs.getRow();
        }catch(Exception e){
          System.out.println(this.getClass()+"GetRecordCount()"+e.toString());
        }
        return Result;
      }}///~:
      

  12.   

    另外,有一个connection类,用来创建一个Connection。支持从配置文件中读取配置信息。
    package com.we.system.db;/**
     * <p>Function: This class is use for create a Database Connection.</p>
     * <p>Title: Museum Relic Magament</p>
     * <p>Description: The first software with Java</p>
     * <p>Copyright: Copyright (c) 2002</p>
     * <p>Company: WestEngine corporation</p>
     * <p>Compose Date: 2002-02-23</p>
     * @author Adai lee
     * @version 0.0.0.1
     */import java.sql.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;public class connection {  private String ConnectionString="";
      private String Driver="";
      private String Type="";
      private String Port="";
      private String Server="";
      private String Database="";
      private String User="";
      private String Password="";
      private String ConfigFile="";  private String idDriver = "DRIVER";
      private String idType = "TYPE";
      private String idPort = "PORT";
      private String idServer = "SERVER";
      private String idDatabase = "DATABASE";
      private String idUser = "USER";
      private String idPassword = "PASSWORD";  /**
       * Build a connection class.
       */
      public connection() {  }  /**
       * Build a connection class with parameters.
       * @param driver The driver name.
       * @param type The Type.
       * @param port The Port.
       * @param server The Server name.
       * @param database The Database.
       * @param user The user name.
       * @param password The password.
       */
      public connection(String driver, String type, String port, String server,
               String database, String user, String password) {
        SetDriver(driver);
        SetType(type);
        SetPort(port);
        SetServer(server);
        SetDatabase(database);
        SetUser(user);
        SetPassword(password);
      }  /**
       * Build a connection class with a config files;
       * @param configfile The config file name.
       */
      public connection(String configfile) {
        LoadConfig(configfile);
      }  /**
       * Set the Config File
       * @param configfile The config file Name
       */
      public void SetConfigFile(String configfile) {
        ConfigFile = configfile;
      }  /**
       * Get the Config File's Name
       * @return The Config File Name
       */
      public String GetConfigFile() {
        return ConfigFile;
      }  /**
       * Set the Database Server name.
       * @param server The machine name.
       */
      public void SetServer(String server) {
        Server = server;
      }  /**
       * Get the Database Server name.
       * @return The Server name.
       */
      public String GetServer() {
        return Server;
      }  /**
       * Set the database name.
       * @param database the Database name.
       */
      public void SetDatabase(String database) {
        Database = database;
      }  /**
       * Get the Database name.
       * @return The Database name.
       */
      public String GetDatabase() {
        return Database;
      }  /**
       * Get the Driver Type.
       * @param type The Driver Type.
       */
      public void SetType(String type) {
        Type = type;
      }  /**
       * Get the Driver Type.
       * @return The Driver Type.
       */
      public String GetType() {
        return Type;
      }  /**
       * Set the port number.
       * @param port The Port No.
       */
      public void SetPort(String port) {
        if (port.toUpperCase().compareTo("")!=0) {
           Port = ":" + port;
        }else
        Port = port;
      }  /**
       * Get the port Number.
       * @return The Port No.
       */
      public String GetPort() {
        return Port;
      }  /**
       * Set the Driver Name.
       * @param driver The driver name.
       */
      public void SetDriver(String driver) {
        Driver = driver;
      }  /**
       * Get the Driver Name.
       * @return The driver name.
       */
      public String GetDriver() {
        return Driver;
      }  /**
       * Set the user name(Login name).
       * @param user
       */
      public void SetUser(String user) {
        User = user;
      }  /**
       * Get the Login Name.
       * @return The login name.
       */
      public String GetUser() {
        return User;
      }  /**
       * Set the password for login into database.
       * @param password The password.
       */
      public void SetPassword(String password) {
        Password = password;
      }  /**
       * Get the current password.
       * @return The password.
       */
      public String GetPassword() {
        return Password;
      }  /**
       * Build the connection string.
       */
      protected void BuildConnectionString() {
        ConnectionString = "jdbc:" + Type +"://" + Server + Port + "/" + Database;  }  /**
       * Load the Connection parameters from a config file.
       */
      public void LoadConfig() {
        Properties connProperties = new Properties();
        try{
          FileInputStream connFileInputStream = new FileInputStream(ConfigFile);
          connProperties.load(connFileInputStream);
          SetDatabase((String)connProperties.get(idDatabase));
          SetDriver((String)connProperties.get(idDriver));
          SetPassword((String)connProperties.get(idPassword));
          SetPort((String)connProperties.get(idPort));
          SetServer((String)connProperties.get(idServer));
          SetType((String)connProperties.get(idType));
          SetUser((String)connProperties.get(idUser));
          connFileInputStream.close();
        }catch(Exception e){
          System.out.println(e.getMessage());
        }
      }  /**
       * Load the Connection paramwters from a config file.
       * @param configfile The config file name.
       */
      public void LoadConfig(String configfile) {
        SetConfigFile(configfile);
        LoadConfig();
      }  /**
       * Build a connection
       * @return the connection
       */
      public Connection BuildConnection(){
        Connection conn = null;
        BuildConnectionString();
        try{
          Class.forName(Driver);
          Properties pr = new Properties();
          pr.setProperty("user",User);
          pr.setProperty("password",Password);
          pr.setProperty("useUnicode","true");
          pr.setProperty("characterEncoding","GB2312");
    //      String info = "user="+User+";password="+Password
    //        +";useUnicode=true;characterEncoding=gb2312";
          conn = DriverManager.getConnection(ConnectionString, pr);
    //      conn = DriverManager.getConnection(ConnectionString,User,Password);
        }catch(Exception e){
          System.out.println(e.getMessage());
        }
        return conn;
      }}///:~
      

  13.   

    配置文件样式如下:
    DRIVER=org.gjt.mm.mysql.Driver
    #DRIVER=com.caucho.jdbc.mysql.Driver
    useUnicode=true
    characterEncoding=gb2312
    TYPE=mysql
    PORT=
    SERVER=localhost
    DATABASE=museum
    USER=root
    PASSWORD=root
      

  14.   

    To sonic616:本来就是一样的嘛BTW, 听你的口气(比如说我要取得这个记录有50个字段,那要写50个GET...()函数了),好像字段很多的样子,你可以用个循环啊,for(i=0;i<50;i++)
    {
      fields[i]=rs.getString(i);
    }当然了,我知道不可能所有的字段都是String的,你再灵活处理一下吧
      

  15.   

    超级感谢adailee(不谈恋爱的铅笔),你贴出了这么详细的东西,真是感动死我了!我这么点儿分都觉得过意不去啦,请来这里继续领分:http://www.csdn.net/expert/topic/493/493836.xml?temp=.5773737顺便请你留个联系方式,这个东西我一时半会儿还试不完,以后还有需要请教的地方继续感谢cosmo(MoMo)请您来这里领分:
    http://www.csdn.net/expert/topic/545/545184.xml?temp=.6981623
    也请你留下一个联系方式,谢谢!!!
      

  16.   

    不用客气,这也是我学习Java过程中的体会。
    我的电子邮件[email protected]