建立一个Derby日历,第2部分 - 嵌入选项(下) - 面向对象网,数据库,基础,原理,学习,对象 - 面向对象技术开发

面向对象技术开发

会员投稿 投稿指南 站长资讯通告:
您的位置: 首页 > 数据库 > 其它数据库 > 正文

建立一个Derby日历,第2部分 - 嵌入选项(下)

来源: www.bianceng.cn 阅读:

对于 EventClass 类,只需要接收用户名和口令并保存到属性中。连接到数据库时,检索并使用该信息。

因为静态使用 Calendar 类,情况略有不同,如 清单 15 所示。

清单 15. Calendar 和用户信息

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import java.sql.ResultSet;

public class Calendar {

   public static String driver =
         "org.apache.derby.jdbc.ClientDriver";

   private static Connection getConnection(String  username,
                   String password) throws  Exception {

    Class.forName(driver).newInstance();
    Connection conn = null;
    conn = DriverManager.getConnection(
         "jdbc:derby://localhost:1527/calendar;user="
                    +username+";password="+password);
    return conn;
   }

   public static EventClass[] getEvents(int eventMonth,
              int eventDay, int eventYear,
              String username, String password)  {
    try {
      Connection conn = getConnection(username,  password);

      Statement s = conn.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
                      ResultSet.CONCUR_READ_ONLY);

      ResultSet rs = s.executeQuery("SELECT * FROM Event  "+
               "where eventMonth="+eventMonth+
               " and eventDay="+eventDay+" and "+
               "eventYear="+eventYear);
      EventClass[] events = null;

      if (!rs.next()){
       return null;
      } else {
       rs.last();
       int numberOfEvents = rs.getRow();
       rs.beforeFirst();

       events = new EventClass[numberOfEvents];
       int thisEventIndex = 0;
       EventClass thisEvent = null;
       while (rs.next()) {
         thisEvent = new EventClass(rs.getInt(1),  username, password);
         thisEvent.setTitle(rs.getString(2));
         thisEvent.setDescription(rs.getString(3));
         thisEvent.setRemindersTo(rs.getString(4));
         thisEvent.setEventMonth(rs.getInt(5));
         thisEvent.setEventDay(rs.getInt(6));
         thisEvent.setEventYear(rs.getInt(7));
         events[thisEventIndex] = thisEvent;
         thisEventIndex = thisEventIndex + 1;
       }
      }

      rs.close();
      s.close();
      conn.close();
      try {
       DriverManager.getConnection(
                "jdbc:derby:;shutdown=true");
      } catch (SQLException se) { }
      return events;

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

   }

   public static void main (String args[]){

    int month = Integer.parseInt(args[0]);
    int day = Integer.parseInt(args[1]);
    int year = Integer.parseInt(args[2]);
    getEvents(month, day, year, args[3], args[4]);
   }
}

Tags:
相关文章列表: