Пример #1
2
  // Takes and image_id, pulls in the image from cache, and goes about
  // encoding it to put it into the database in a transaction.  The last
  // query in the transaction records the image having been stored.
  protected void storeImage(int image_id) throws Exception {
    PhotoImage p = new PhotoImage(image_id);
    SpyDB pdb = getDB();
    Connection db = null;
    Statement st = null;
    Vector v = p.getImage();
    System.err.println(
        "Storer: Got image for " + image_id + " " + v.size() + " lines of data to store.");
    try {
      int i = 0, n = 0;
      db = pdb.getConn();
      db.setAutoCommit(false);
      st = db.createStatement();
      BASE64Encoder base64 = new BASE64Encoder();
      String data = "";

      for (; i < v.size(); i++) {
        String tmp = base64.encodeBuffer((byte[]) v.elementAt(i));
        tmp = tmp.trim();

        if (data.length() < 2048) {
          data += tmp + "\n";
        } else {
          storeQuery(image_id, n, st, data);
          data = tmp;
          n++;
        }
      }
      // OK, this is sick, but another one right now for the spare.
      if (data.length() > 0) {
        System.err.println("Storer:  Storing spare.");
        storeQuery(image_id, n, st, data);
        n++;
      }
      System.err.println("Storer:  Stored " + n + " lines of data for " + image_id + ".");
      st.executeUpdate(
          "update upload_log set stored=datetime(now())\n" + "\twhere photo_id = " + image_id);
      db.commit();
      // Go ahead and generate a thumbnail.
      p.getThumbnail();
    } catch (Exception e) {
      // If anything happens, roll it back.
      if (st != null) {
        try {
          db.rollback();
        } catch (Exception e3) {
          // Nothing
        }
      }
    } finally {
      if (db != null) {
        try {
          db.setAutoCommit(true);
        } catch (Exception e) {
          System.err.println("Error:  " + e);
        }
      }
      pdb.freeDBConn();
    }
  }
Пример #2
1
 static void attributeMean() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     Statement meanQuery = con.createStatement();
     ResultSet mean = meanQuery.executeQuery("select AVG(sal) from employ where sal IS NOT NULL");
     if (mean.next()) {
       fill = con.createStatement();
       fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + mean.getInt(1) + ")");
     }
     /*fill = con.createStatement();
     fill.executeUpdate("UPDATE employ set sal = COALESCE(sal,AVG(sal))");*/
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println("Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
Пример #3
0
 static void probableValue() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     Statement freqQuery = con.createStatement();
     ResultSet freq =
         freqQuery.executeQuery(
             "select sal,count(*) as total from employ group by sal order by total desc");
     if (freq.next()) {
       fill = con.createStatement();
       fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + freq.getInt(1) + ")");
     }
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println(">>Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
  private static void dropCourse(Connection conn, String stu_no) throws SQLException {
    String cno = readEntry("Course number: ");
    String sno = readEntry("Section number : ");

    String chks =
        "SELECT g.Section_identifier FROM SECTION s, GRADE_REPORT g where s.Section_identifier=g.Section_identifier AND s.Course_number='"
            + cno
            + "' AND g.Section_identifier="
            + sno
            + " AND s.Semester='Spring' AND s.Year=TO_DATE('2007','YYYY') AND g.Student_number="
            + stu_no;
    Statement s3 = conn.createStatement();
    ResultSet r3 = s3.executeQuery(chks);

    if (r3.next()) {
      String del =
          "DELETE FROM GRADE_REPORT WHERE Student_number="
              + stu_no
              + " AND Section_identifier="
              + sno;
      Statement s4 = conn.createStatement();
      try {
        s4.executeUpdate(del);
        System.out.println("Course dropped");
      } catch (SQLException e) {
        System.out.println("Cannot drop a course from table");
      }
    } else {
      System.out.println("Enrollment data not found. Check the input and try again.");
    }
  }
Пример #5
0
 static void specificAttributeMean() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     fill = con.createStatement();
     fill.executeUpdate(
         "UPDATE employ a set sal = (select AVG(sal) from employ where sal IS NOT NULL and grade = (select grade from employ b where sal IS NULL and a.grade=b.grade and ROWNUM <= 1)) where sal IS NULL");
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println(">>Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
Пример #6
0
 static void globalConstant() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     fill = con.createStatement();
     fill.executeUpdate("UPDATE employ set sal = " + GlobalConstant + " where sal IS NULL");
     // fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + GlobalConstant + ")");
     // System.out.println("Entered..!");
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println("Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
Пример #7
0
  private synchronized void init() throws SQLException {
    if (isClosed) return;

    // do tables exists?
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(TABLE_NAMES_SELECT_STMT);

    ArrayList<String> missingTables = new ArrayList(TABLES.keySet());
    while (rs.next()) {
      String tableName = rs.getString("name");
      missingTables.remove(tableName);
    }

    for (String missingTable : missingTables) {
      try {
        Statement createStmt = conn.createStatement();
        // System.out.println("Adding table "+ missingTable);
        createStmt.executeUpdate(TABLES.get(missingTable));
        createStmt.close();

      } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
      }
    }
  }
  private static void addCourse(Connection conn, String stu_no) throws SQLException {
    String cno = readEntry("Course number : ");
    String sno = readEntry("Section number : ");

    String course_query =
        "SELECT Section_identifier FROM SECTION WHERE Section_identifier="
            + sno
            + " AND Course_number='"
            + cno
            + "' AND Semester='Spring' AND YEAR=TO_DATE('2007','YYYY')";
    // System.out.println(course_query);
    Statement s1 = conn.createStatement();
    ResultSet r1 = s1.executeQuery(course_query);
    if (r1.next()) {
      String addc =
          "INSERT INTO GRADE_REPORT (Student_number, Section_identifier, Grade) VALUES ("
              + stu_no
              + ", "
              + sno
              + ", 'NULL')";
      Statement s2 = conn.createStatement();
      System.out.println(addc);
      try {
        s2.executeUpdate(addc);
        System.out.println("Enrollment successfull");
      } catch (SQLException e) {
        System.out.println("Cannot add course into table");
      }
    } else {
      System.out.println("Course not found");
    }
    s1.close();
  }
Пример #9
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
Пример #10
0
  /**
   * Remove a student from a particular course. Also Deletes all the quiz vizualisation files in the
   * student's directory which relates to the course. Caution: vizualisation file will be deleted
   * eventhough it also relates to another course if the student is also registered to that course.
   * (FIX ME!) Throws InvalidDBRequestException if the student is not registered in the course,
   * error occured during deletion, or other exception occured.
   *
   * @param username student's user name
   * @param courseID course id (course number + instructor name)
   * @throws InvalidDBRequestException
   */
  public void deleteStudent(String username, String courseID) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      int count = 0;

      // check if student registered to the course
      rs =
          stmt.executeQuery(
              "select * from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (!rs.next())
        throw new InvalidDBRequestException("Student is not registered to the course");

      // remove student from the course
      count =
          stmt.executeUpdate(
              "delete from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (count != 1) throw new InvalidDBRequestException("Error occured during deletion!");

      // delete the quiz visualization files
      rs =
          stmt.executeQuery(
              "select distinct unique_id, s.test_name from scores s, courseTest t "
                  + "where s.test_name = t.test_name "
                  + "and course_id = '"
                  + courseID
                  + "' "
                  + "and user_login = '******'");
      while (rs.next()) {
        deleteVisualization(rs.getString(1), username, rs.getString(2));
        count =
            stmt.executeUpdate("delete from scores where unique_id = " + rs.getString(1).trim());
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addstudent: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Пример #11
0
  public String checkValidLogin(String myUserName, String myPW) {

    try {
      Class.forName(javaSQLDriverPath);
      Connection conn =
          (Connection) DriverManager.getConnection(ConnectionPath, ConnectionUser, ConnectionPW);
      Statement st = conn.createStatement();
      String query = "Select * from User";

      ResultSet rs = st.executeQuery(query);
      while (rs.next()) {
        // return rs.getString("Username");
        if (myUserName.equals(rs.getString("Username"))) {
          if (myPW.equals(rs.getString("Password"))) {
            setUserVariables(myUserName);
            return "success";
          } else {
            return "wrongPassword";
          }
        }
      }

      rs.close();
      st.close();
      conn.close();

      return "userNotFound";
    } catch (Exception e) {

      return e.getMessage();
    }
  }
Пример #12
0
  public void carga_default() {

    Connection con = null;
    Statement st = null;
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql://localhost/rsu_inventario", "root", pass);
      try {
        st = con.createStatement();
        st.executeUpdate(
            "INSERT INTO ADMIN VALUES ('174183767','msX','msx','estudiante','santiago',"
                + "'2130','3030303','30303030','los valdios 3030','*****@*****.**',12345);");

      } catch (SQLException s) {

        SQL_FORM error = new SQL_FORM();
        JOptionPane.showMessageDialog(error, "error al ingresar datos");

        // SQL_FORM error = new SQL_FORM();
        JOptionPane.showMessageDialog(error, s, "alert", JOptionPane.ERROR_MESSAGE);

      } finally {
        con.close();
        st.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #13
0
  public static void customStartAll(Connection conn) throws SQLException {
    String method = "customStartAll";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      int id = 0;
      int gpfdistPort = 0;
      String strSQL = "SELECT id\n";
      strSQL += "FROM os.custom_sql";

      ResultSet rs = stmt.executeQuery(strSQL);
      while (rs.next()) {
        id = rs.getInt(1);
        gpfdistPort = GpfdistRunner.customStart(OSProperties.osHome);

        strSQL = "INSERT INTO os.ao_custom_sql\n";
        strSQL +=
            "(id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, gpfdist_port)\n";
        strSQL +=
            "SELECT id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, "
                + gpfdistPort
                + "\n";
        strSQL += "FROM os.custom_sql\n";
        strSQL += "WHERE id = " + id;

        stmt.executeUpdate(strSQL);
      }
    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Пример #14
0
  public static void failJobs(Connection conn) throws SQLException {
    String method = "failJobs";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      String strSQL =
          "INSERT INTO os.ao_queue (queue_id, status, queue_date, start_date, end_date, "
              + "error_message, num_rows, id, refresh_type, target_schema_name, target_table_name, target_append_only, "
              + "target_compressed, target_row_orientation, source_type, source_server_name, source_instance_name, "
              + "source_port, source_database_name, source_schema_name, source_table_name, source_user_name, "
              + "source_pass, column_name, sql_text, snapshot) "
              + "SELECT queue_id, 'failed' as status, queue_date, start_date, now() as end_date, "
              + "'Outsourcer stop requested' as error_message, num_rows, id, refresh_type, target_schema_name, "
              + "target_table_name, target_append_only, target_compressed, target_row_orientation, source_type, "
              + "source_server_name, source_instance_name, source_port, source_database_name, source_schema_name, "
              + "source_table_name, source_user_name, source_pass, column_name, sql_text, snapshot "
              + "FROM os.queue WHERE status = 'queued'";

      stmt.executeUpdate(strSQL);

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Пример #15
0
  public static String getVersion(Connection conn) throws SQLException {
    String method = "getVersion";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL =
          "SELECT CASE "
              + "WHEN POSITION ('HAWQ 2.0.1' in version) > 0 THEN 'HAWQ_2_0_1' "
              + "WHEN POSITION ('HAWQ 2.0.0' in version) > 0 THEN 'HAWQ_2_0_0' "
              + "WHEN POSITION ('HAWQ 1' in version) > 0 THEN 'HAWQ_1' "
              + "WHEN POSITION ('HAWQ' in version) = 0 AND POSITION ('Greenplum Database' IN version) > 0 THEN 'GPDB' "
              + "ELSE 'OTHER' END "
              + "FROM version()";
      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Пример #16
0
  public static String getVariable(Connection conn, String name) throws SQLException {
    String method = "getVariable";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL = "SELECT os.fn_get_variable('" + name + "')";

      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Пример #17
0
  /**
   * Deletes an instructor from the database. Deletes the instructor's courses by invoking the
   * deleteCourse method. Throws InvalidDBRequestException if instructor not in the database or
   * other database connection problems.
   *
   * @see deleteCourse
   * @param instructor instructor's user name
   * @throws InvalidDBRequestException
   */
  public void deleteInstructor(String instructor) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete the instructor's courses
      ResultSet rs =
          stmt.executeQuery(
              "select course_num from course where instructor = '" + instructor + "'");
      while (rs.next()) deleteCourse(rs.getString(1).trim(), instructor);

      // delete the instructor's record
      count = stmt.executeUpdate("delete from instructor where login ='******'");

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Пример #18
0
  // Get a list of images that have been added, but not yet added into
  // the database.
  protected void doFlush() {
    SpyDB pdb = getDB();
    Vector v = null;
    try {
      Connection db = pdb.getConn();
      Statement st = db.createStatement();
      String query = "select * from upload_log where stored is null";
      ResultSet rs = st.executeQuery(query);
      v = new Vector();
      while (rs.next()) {
        v.addElement(rs.getString("photo_id"));
      }
    } catch (Exception e) {
      // Do nothing, we'll try again later.
    } finally {
      pdb.freeDBConn();
    }

    // Got the vector, now store the actual images.  This is done so
    // that we don't hold the database connection open whlie we're
    // making the list *and* getting another database connection to act
    // on it.
    if (v != null) {
      try {
        for (int i = 0; i < v.size(); i++) {
          String stmp = (String) v.elementAt(i);
          storeImage(Integer.valueOf(stmp).intValue());
        }
      } catch (Exception e) {
        // Don't care, we'll try again soon.
      }
    }
  }
Пример #19
0
  /**
   * Delete a student from the database. Also deletes the student's folders. Throws
   * InvalidDBRequestException if any error in database connection.
   *
   * @param username student's user name
   * @throws InvalidDBRequestException
   */
  private void purgeStudent(String username) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete from scores
      count = stmt.executeUpdate("delete from scores where user_login = '******'");

      // delete from student
      count = stmt.executeUpdate("delete from student where login = '******'");

      // delete student's folder
      File studentDir = new File("./StudentQuizzes/" + username);
      if (!(studentDir.delete())) {
        System.err.println("Error in deleting folder for student: " + username);
      }

      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Пример #20
0
  public void conectarBaseDeDatos() {
    try {
      final String CONTROLADOR = "org.postgresql.Driver";
      Class.forName(CONTROLADOR);
      // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
      conexion =
          DriverManager.getConnection(
              "jdbc:postgresql://" + main.ipSeleccionada + "/" + objUtils.nameBD, user, pass);
      // conexion = DriverManager.getConnection("jdbc:postgresql://127.0.0.1/goliak_jg", "postgres",
      // "majcp071102kaiser");

      sentencia = conexion.createStatement();
      /*JOptionPane.showMessageDialog(null, "si conecta");*/
    } catch (ClassNotFoundException ex1) {
      // ex1.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage());
      System.exit(1);
    } catch (SQLException ex) {
      // ex.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(
          null,
          "Error Creacion Statement."
              + ex.getMessage()
              + " / "
              + url
              + " / "
              + user
              + " / "
              + pass);
      System.exit(1);
    }
  }
Пример #21
0
 // AQUI VOYA  OBTENER EL SERVDUIOR QUEMADO EN UN ARCHIVO DE TEXTO
 public void conectarBaseDeDatos2() {
   try {
     final String CONTROLADOR = "org.postgresql.Driver";
     Class.forName(CONTROLADOR);
     // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
     conexion = DriverManager.getConnection(url2, user, pass);
     sentencia = conexion.createStatement();
     /*JOptionPane.showMessageDialog(null, "si conecta");*/
   } catch (ClassNotFoundException ex1) {
     // ex1.printStackTrace();
     javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage());
     System.exit(1);
   } catch (SQLException ex) {
     // ex.printStackTrace();
     javax.swing.JOptionPane.showMessageDialog(
         null,
         "Error Creacion Statement."
             + ex.getMessage()
             + " / "
             + url2
             + " / "
             + user
             + " / "
             + pass);
     System.exit(1);
   }
 }
Пример #22
0
  /**
   * Check the user's name and password and verify that the user is an instructor. Throws
   * InvalidDBRequestException if user is not an instructor, wrong password, or if any error occured
   * to the database connection.
   *
   * @param name user's user name
   * @param pass user's password
   * @throws InvalidDBRequestException
   */
  public void instructorLogin(String name, String pass) throws InvalidDBRequestException {
    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // check if instructor
      rs = stmt.executeQuery("select password from instructor where login = '******'");
      if (!rs.next()) {
        if (debug) System.out.println("User not found in the instructor table");
        throw new InvalidDBRequestException("Instructor not registered");
      }

      // check password
      if (!rs.getString(1).equals(pass)) {
        if (debug) System.out.println("Invalid password for user: "******"Invalid password for user: "******"Invalid SQL in instructor login: "******"???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }
  }
  // execute and get results
  private void execute(Connection conn, String text, Writer writer, boolean commaSeparator)
      throws SQLException {

    BufferedWriter buffer = new BufferedWriter(writer);
    Statement stmt = conn.createStatement();
    stmt.execute(text);
    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData metadata = rs.getMetaData();
    int nbCols = metadata.getColumnCount();
    String[] labels = new String[nbCols];
    int[] colwidths = new int[nbCols];
    int[] colpos = new int[nbCols];
    int linewidth = 1;

    // read each occurrence
    try {
      while (rs.next()) {
        for (int i = 0; i < nbCols; i++) {
          Object value = rs.getObject(i + 1);
          if (value != null) {
            buffer.write(value.toString());
            if (commaSeparator) buffer.write(",");
          }
        }
      }
      buffer.flush();
      rs.close();
    } catch (IOException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      // ok, exit from the loop
    } catch (SQLException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
    }
  }
Пример #24
0
  public void conectarBDdinamic(String ip) {

    if (ip == null) {
      ip = "192.168.8.231";
    }
    url = "jdbc:postgresql://" + ip + "/ventasalm";
    // javax.swing.JOptionPane.showMessageDialog(null, url);
    String estado;
    try {

      final String CONTROLADOR = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
      Class.forName(CONTROLADOR);
      // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
      conexion = DriverManager.getConnection(url, user, pass);
      sentencia = conexion.createStatement();
      // estado="Conectado Correctamente";
    } catch (ClassNotFoundException ex1) {
      ex1.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver");
      estado = "Servidor no esta disponible";
      // System.exit(1);
    } catch (SQLException ex) {
      ex.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Creacion Statement");
      estado = "Servidor no esta disponible";
      // System.exit(1);
    }
    // return estado;
  }
Пример #25
0
  /**
   * Deletes students who are older than a certain number of years and not registered to any course.
   *
   * @param year students older than year are candidates to be deleted
   * @throws InvalidDBRequestException
   */
  public void deleteOldStudent(int year) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();

      // query all student who have been in the database longer than a number of years and not
      // registered to any course
      ResultSet rs =
          stmt.executeQuery(
              "select login, count(course_id) "
                  + "from student s left join courseRoster r on login = user_login "
                  + "where date_entered < SUBDATE(now(), INTERVAL "
                  + new String().valueOf(year).trim()
                  + " YEAR) "
                  + "group by login, date_entered");
      // delete them
      while (rs.next()) if (rs.getInt(2) == 0) purgeStudent(rs.getString(1).trim());

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Пример #26
0
  public List<ClientEventEntry> findLogEvents(
      List<SearchConstraint> constraints, List<String> orderBy, int offset, int limit, Connection c)
      throws SQLException {
    StringBuffer sql =
        new StringBuffer(
            "select e.event_id, e.customer_id, e.user_id, e.event_time, e.description, e.has_log_file from dat_client_log_events e ");
    appendWhere(sql, constraints, s_propToColumnMap);
    appendOrderBy(sql, orderBy, "e.event_id desc", s_propToColumnMap);
    appendLimits(sql, offset, limit);

    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = c.createStatement();
      rs = stmt.executeQuery(sql.toString());
      List<ClientEventEntry> results = new ArrayList<ClientEventEntry>();
      while (rs.next()) {
        ClientEventEntry entry =
            new ClientEventEntry(
                rs.getInt(1),
                rs.getInt(2),
                rs.getInt(3),
                resolveDate(rs.getTimestamp(4)),
                rs.getString(5),
                rs.getInt(6) != 0);
        results.add(entry);
      }
      return results;
    } finally {
      DbUtils.safeClose(rs);
      DbUtils.safeClose(stmt);
    }
  }
Пример #27
0
  /**
   * Gets a list of courses that belongs to an instructor. Throws InvalidDBRequestException if any
   * error occured to the database connection.
   *
   * @param name the instructor's user name
   * @return a vector containing the list of courses
   * @throws InvalidDBRequestException
   */
  public Vector getCourseList(String name) throws InvalidDBRequestException {
    Vector courseList = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // get the course list
      rs =
          stmt.executeQuery(
              "select course_num, course_name from course where instructor = '"
                  + name
                  + "' order by course_num");
      while (rs.next()) courseList.add(rs.getString(1) + " - " + rs.getString(2));

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getCourseList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }

    return courseList;
  }
Пример #28
0
  /* to search the DB table for req. video*/
  boolean search(String file) {

    boolean found = false;

    Connection con = null;
    String url =
        "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};  DBQ=D://db.mdb; DriverID=22;READONLY=true;";

    try {
      con = DriverManager.getConnection(url, "", "");
      try {
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("SELECT video FROM p3");
        while (rs.next()) {
          String colvalue = rs.getString("video");
          if (colvalue.equalsIgnoreCase(file)) found = true;
        }

      } catch (SQLException s) {
        System.out.println("SQL statement is not executed!");
      }
    } catch (Exception e) {
      System.out.println(e);
    }
    return found;
  }
Пример #29
0
  public static void main(String args[]) {
    int myport = 9090;
    Socket s;
    ServerSocket ss;
    BufferedReader fromSoc, fromKbd;
    PrintStream toSoc;
    String line, msg;
    try {
      s = new Socket("169.254.63.10", 6016);
      System.out.println("enter line");
      System.out.println("connected");
      toSoc = new PrintStream(s.getOutputStream());

      toSoc.println(myport);
      String url =
          "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=D://db.mdb; DriverID=22;READONLY=true;";

      Connection con = DriverManager.getConnection(url, "", "");
      Statement st = con.createStatement();
      String ip = "169.254.63.10";
      int port = 6016;
      String video = "rooney";

      st.executeUpdate(
          " insert into p3 values('" + ip + "' , '" + port + "' , '" + video + "' );  ");

      fun();

    } catch (Exception e) {

      System.out.println("exception" + e);
    }
  }
Пример #30
-1
  public List<Empleado> getAllEmpleados() {
    List ll = new LinkedList();
    Statement st;
    ResultSet rs;
    String url = "jdbc:mysql://localhost:3306/food";
    String user = "******";
    String pass = "******";
    String driver = "com.mysql.jdbc.Driver";

    try (Connection connection = DriverManager.getConnection(url, user, pass)) {
      Class.forName(driver);
      st = connection.createStatement();
      String recordQuery = ("Select * from empleados");
      rs = st.executeQuery(recordQuery);
      while (rs.next()) {
        Integer id = rs.getInt("idEmpleados");
        String name = rs.getString("Nombre");
        String telf = rs.getString("Telefono");
        ll.add(new Empleado(id, name, telf));
        /// System.out.println(id +","+ name +","+ apellido +","+ cedula +","+ telf +"
        // "+direccion+"");
      }

    } catch (ClassNotFoundException | SQLException ex) {
      Logger.getLogger(MenuEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ll;
  }